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:

<?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="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd">
 
    <services>
        <service id="fos_user.user_provider.email" class="AppBundle\Security\EmailProvider" public="false">
            <argument type="service" id="fos_user.user_manager" />
        </service>
    </services>
</container>

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

security:
     providers:
        fos_userbundle:
            id: fos_user.user_provider.email

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 infzanoza@gmail.com for services of experienced web developer.

Follow @infernosquad

LEAVE A COMMENT