Problems trying to login in your app with the email instead of the username? Learn how to enable both ways !

With the default configuration of your userbundle available at the setup guide in the official FOSUserBundle repository, you will need an username, your email and the password in order to register yourself in the default /register module.

A default login after your registration, can be easily achieved with the username and password. But if you try to sign in with your email, an uncomfortable "credentials invalid" error message will be the response of your form, although you enter the correct email account, this message will appear again and again.

Or if your oAuth api uses FOSUserBundle as the default user provider, and you try to use the grant_type password (sending the user credentials in the parameters) an authentication error message is returned because your username parameter is the email of the user.

This problem can be easily solved changing the user provider property in your security.yml file (and config.yml if you use FOSOAuthServerBundle).

FOSUserBundle

Update the fos_userbundle property in the providers of your security.yml file:

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
        #  Your id property should look like :
        #   id: fos_user.user_provider.username 
        #  Change to 
            id: fos_user.user_provider.username_email

Then you'll be able to login with email and username from the default or customized login forms.

FOSOAuthServerBundle

Update the user_provider property in the configuration of the config.yml file.

fos_oauth_server:
    db_driver: orm        
    client_class:        easymedic\apiBundle\Entity\Client
    access_token_class:  easymedic\apiBundle\Entity\AccessToken
    refresh_token_class: easymedic\apiBundle\Entity\RefreshToken
    auth_code_class:     easymedic\apiBundle\Entity\AuthCode
    # Your actual service> user_provider property, should look like
    #service:
    #    user_provider: fos_user.user_provider.username
    # Change it for
    service:
        user_provider: fos_user.user_provider.username_email

Then you'll be able to login to your project with username or email (canonical email) in the authentication via API (oauth tokens grant_type password).


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors