Symfony 4 was released on November 30th.
Update now to the best Symfony ever!

How to Create a Custom Form Password Authenticator

How to Create a Custom Form Password Authenticator

Imagine you want to allow access to your website only between 2pm and 4pm UTC. Before Symfony 2.4, you had to create a custom token, factory, listener and provider. In this entry, you'll learn how to do this for a login form (i.e. where your user submits their username and password). Before Symfony 2.6, you had to use the password encoder to authenticate the user password.

The Password Authenticator

New in version 2.6: The UserPasswordEncoderInterface interface was introduced in Symfony 2.6.

First, create a new class that implements SimpleFormAuthenticatorInterface. Eventually, this will allow you to create custom logic for authenticating the user:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// src/AppBundle/Security/TimeAuthenticator.php
namespace AppBundle\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\SimpleFormAuthenticatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class TimeAuthenticator implements SimpleFormAuthenticatorInterface
{
    private $encoder;

    public function __construct(UserPasswordEncoderInterface $encoder)
    {
        $this->encoder = $encoder;
    }

    public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {
        try {
            $user = $userProvider->loadUserByUsername($token->getUsername());
        } catch (UsernameNotFoundException $e) {
            throw new AuthenticationException('Invalid username or password');
        }

        $passwordValid = $this->encoder->isPasswordValid($user, $token->getCredentials());

        if ($passwordValid) {
            $currentHour = date('G');
            if ($currentHour < 14 || $currentHour > 16) {
                throw new AuthenticationException(
                    'You can only log in between 2 and 4!',
                    412 // HTTP 412 Precondition Failed
                );
            }

            return new UsernamePasswordToken(
                $user,
                $user->getPassword(),
                $providerKey,
                $user->getRoles()
            );
        }

        throw new AuthenticationException('Invalid username or password');
    }

    public function supportsToken(TokenInterface $token, $providerKey)
    {
        return $token instanceof UsernamePasswordToken
            && $token->getProviderKey() === $providerKey;
    }

    public function createToken(Request $request, $username, $password, $providerKey)
    {
        return new UsernamePasswordToken($username, $password, $providerKey);
    }
}

How it Works

Great! Now you just need to setup some Configuration. But first, you can find out more about what each method in this class does.

1) createToken

When Symfony begins handling a request, createToken() is called, where you create a TokenInterface object that contains whatever information you need in authenticateToken() to authenticate the user (e.g. the username and password).

Whatever token object you create here will be passed to you later in authenticateToken().

2) supportsToken

After Symfony calls createToken(), it will then call supportsToken() on your class (and any other authentication listeners) to figure out who should handle the token. This is just a way to allow several authentication mechanisms to be used for the same firewall (that way, you can for instance first try to authenticate the user via a certificate or an API key and fall back to a form login).

Mostly, you just need to make sure that this method returns true for a token that has been created by createToken(). Your logic should probably look exactly like this example.

3) authenticateToken

If supportsToken() returns true, Symfony will now call authenticateToken(). Your job here is to check that the token is allowed to log in by first getting the User object via the user provider and then, by checking the password and the current time.

Note

The "flow" of how you get the User object and determine whether or not the token is valid (e.g. checking the password), may vary based on your requirements.

Ultimately, your job is to return a new token object that is "authenticated" (i.e. it has at least 1 role set on it) and which has the User object inside of it.

Inside this method, the password encoder is needed to check the password's validity:

$passwordValid = $this->encoder->isPasswordValid($user, $token->getCredentials());

This is a service that is already available in Symfony and it uses the password algorithm that is configured in the security configuration (e.g. security.yml) under the encoders key. Below, you'll see how to inject that into the TimeAuthenticator.

Configuration

Now, configure your TimeAuthenticator as a service:

  • YAML
    1
    2
    3
    4
    5
    6
    7
    # app/config/config.yml
    services:
        # ...
    
        time_authenticator:
            class:     AppBundle\Security\TimeAuthenticator
            arguments: ["@security.password_encoder"]
    
  • XML
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    <!-- app/config/config.xml -->
    <?xml version="1.0" ?>
    <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="time_authenticator"
                class="AppBundle\Security\TimeAuthenticator"
            >
                <argument type="service" id="security.password_encoder" />
            </service>
        </services>
    </container>
    
  • PHP
    1
    2
    3
    4
    5
    6
    7
    8
    // app/config/config.php
    use AppBundle\Security\TimeAuthenticator;
    use Symfony\Component\DependencyInjection\Reference;
    
    // ...
    
    $container->register('time_authenticator', TimeAuthenticator::class)
        ->addArgument(new Reference('security.password_encoder'));
    

Then, activate it in the firewalls section of the security configuration using the simple_form key:

  • YAML
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    # app/config/security.yml
    security:
        # ...
    
        firewalls:
            secured_area:
                pattern: ^/admin
                # ...
                simple_form:
                    authenticator: time_authenticator
                    check_path:    login_check
                    login_path:    login
    
  • XML
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <!-- app/config/security.xml -->
    <?xml version="1.0" encoding="UTF-8"?>
    <srv:container xmlns="http://symfony.com/schema/dic/security"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:srv="http://symfony.com/schema/dic/services"
        xsi:schemaLocation="http://symfony.com/schema/dic/services
            http://symfony.com/schema/dic/services/services-1.0.xsd">
        <config>
            <!-- ... -->
    
            <firewall name="secured_area"
                pattern="^/admin"
                >
                <simple-form authenticator="time_authenticator"
                    check-path="login_check"
                    login-path="login"
                />
            </firewall>
        </config>
    </srv:container>
    
  • PHP
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    // app/config/security.php
    
    // ..
    
    $container->loadFromExtension('security', array(
        'firewalls' => array(
            'secured_area'    => array(
                'pattern'     => '^/admin',
                'simple_form' => array(
                    'provider'      => ...,
                    'authenticator' => 'time_authenticator',
                    'check_path'    => 'login_check',
                    'login_path'    => 'login',
                ),
            ),
        ),
    ));
    

The simple_form key has the same options as the normal form_login option, but with the additional authenticator key that points to the new service. For details, see Form Login Configuration.

If creating a login form in general is new to you or you don't understand the check_path or login_path options, see How to Customize Redirect After Form Login.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.