Custom Email Provider in FOSUserBundle

April 18, 2016 | No Comments | Programming | FOSUserBundle PHP Symfony2

In this article I will show you a example of custom user provider in FOSUserBundle.

Let us imagine that we want to authenticate user only by email. In the latest version of this bundle you can authenticate user by username or by username || email combination. Code is pretty simple. You need only inject custom user provider.

First, create EmailProvider.php:

namespace AppBundle\Security;
use FOS\UserBundle\Security\UserProvider;
class EmailProvider extends UserProvider
     * {@inheritDoc}
    protected function findUser($username)
        //Any logic can be inserted here
        return $this->userManager->findUserByEmail($username);

Next, we need to override default FOSUserBundle Email provider. As alternative we can create new one with unique service id. Just inject needed service. For example:

<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns=""
        <service id="" class="AppBundle\Security\EmailProvider" public="false">
            <argument type="service" id="fos_user.user_manager" />

Last, we need add our provider in security.yml:


That’s it. You don’t even need third party bundles like FOSUserBundle for custom providers┬ábut it’s more easier to build authentication system with it.

About the Author / Artem Zhuravlev

Artem Zhuravlev. Web developer. Blog writer.

Need help with your website ? Contact with me by email for services of experienced web developer.

Follow @infernosquad