Authentication

Authentication

When a request points to a secured area, and one of the listeners from the firewall map is able to extract the user’s credentials from the current Symfony\Component\HttpFoundation\Request object, it should create a token, containing these credentials. The next thing the listener should do is ask the authentication manager to validate the given token, and return an authenticated token if the supplied credentials were found to be valid. The listener should then store the authenticated token using the token storage:

  1. use Symfony\Component\HttpKernel\Event\RequestEvent;
  2. use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
  3. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  4. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  5. class SomeAuthenticationListener
  6. {
  7. /**
  8. * @var TokenStorageInterface
  9. */
  10. private $tokenStorage;
  11. /**
  12. * @var AuthenticationManagerInterface
  13. */
  14. private $authenticationManager;
  15. /**
  16. * @var string Uniquely identifies the secured area
  17. */
  18. private $providerKey;
  19. // ...
  20. public function __invoke(RequestEvent $event)
  21. {
  22. $request = $event->getRequest();
  23. $username = ...;
  24. $password = ...;
  25. $unauthenticatedToken = new UsernamePasswordToken(
  26. $username,
  27. $password,
  28. $this->providerKey
  29. );
  30. $authenticatedToken = $this
  31. ->authenticationManager
  32. ->authenticate($unauthenticatedToken);
  33. $this->tokenStorage->setToken($authenticatedToken);
  34. }
  35. }

Note

A token can be of any class, as long as it implements Symfony\Component\Security\Core\Authentication\Token\TokenInterface.

The Authentication Manager

The default authentication manager is an instance of Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager:

  1. use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;
  2. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  3. // instances of Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface
  4. $providers = [...];
  5. $authenticationManager = new AuthenticationProviderManager($providers);
  6. try {
  7. $authenticatedToken = $authenticationManager
  8. ->authenticate($unauthenticatedToken);
  9. } catch (AuthenticationException $exception) {
  10. // authentication failed
  11. }

The AuthenticationProviderManager, when instantiated, receives several authentication providers, each supporting a different type of token.

Note

You may write your own authentication manager, the only requirement is that it implements Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface.

Authentication Providers

Each provider (since it implements Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface) has a [supports()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Security/Core/Authentication/Provider/AuthenticationProviderInterface.php "Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface::supports()") method by which the AuthenticationProviderManager can determine if it supports the given token. If this is the case, the manager then calls the provider’s [authenticate()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Security/Core/Authentication/Provider/AuthenticationProviderInterface.php "Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface::authenticate()") method. This method should return an authenticated token or throw an Symfony\Component\Security\Core\Exception\AuthenticationException (or any other exception extending it).

Authenticating Users by their Username and Password

An authentication provider will attempt to authenticate a user based on the credentials they provided. Usually these are a username and a password. Most web applications store their user’s username and a hash of the user’s password combined with a randomly generated salt. This means that the average authentication would consist of fetching the salt and the hashed password from the user data storage, hash the password the user has just provided (e.g. using a login form) with the salt and compare both to determine if the given password is valid.

This functionality is offered by the Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider. It fetches the user’s data from a Symfony\Component\Security\Core\User\UserProviderInterface, uses a Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface to create a hash of the password and returns an authenticated token if the password was valid:

  1. use Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider;
  2. use Symfony\Component\Security\Core\Encoder\EncoderFactory;
  3. use Symfony\Component\Security\Core\User\InMemoryUserProvider;
  4. use Symfony\Component\Security\Core\User\UserChecker;
  5. $userProvider = new InMemoryUserProvider(
  6. [
  7. 'admin' => [
  8. // password is "foo"
  9. 'password' => '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg==',
  10. 'roles' => ['ROLE_ADMIN'],
  11. ],
  12. ]
  13. );
  14. // for some extra checks: is account enabled, locked, expired, etc.
  15. $userChecker = new UserChecker();
  16. // an array of password encoders (see below)
  17. $encoderFactory = new EncoderFactory(...);
  18. $daoProvider = new DaoAuthenticationProvider(
  19. $userProvider,
  20. $userChecker,
  21. 'secured_area',
  22. $encoderFactory
  23. );
  24. $daoProvider->authenticate($unauthenticatedToken);

Note

The example above demonstrates the use of the “in-memory” user provider, but you may use any user provider, as long as it implements Symfony\Component\Security\Core\User\UserProviderInterface. It is also possible to let multiple user providers try to find the user’s data, using the Symfony\Component\Security\Core\User\ChainUserProvider.

The Password Encoder Factory

The Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider uses an encoder factory to create a password encoder for a given type of user. This allows you to use different encoding strategies for different types of users. The default Symfony\Component\Security\Core\Encoder\EncoderFactory receives an array of encoders:

  1. use Acme\Entity\LegacyUser;
  2. use Symfony\Component\Security\Core\Encoder\EncoderFactory;
  3. use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
  4. use Symfony\Component\Security\Core\User\User;
  5. $defaultEncoder = new MessageDigestPasswordEncoder('sha512', true, 5000);
  6. $weakEncoder = new MessageDigestPasswordEncoder('md5', true, 1);
  7. $encoders = [
  8. User::class => $defaultEncoder,
  9. LegacyUser::class => $weakEncoder,
  10. // ...
  11. ];
  12. $encoderFactory = new EncoderFactory($encoders);

Each encoder should implement Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface or be an array with a class and an arguments key, which allows the encoder factory to construct the encoder only when it is needed.

Creating a custom Password Encoder

There are many built-in password encoders. But if you need to create your own, it needs to follow these rules:

  1. The class must implement Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface (you can also extend Symfony\Component\Security\Core\Encoder\BasePasswordEncoder);

  2. The implementations of [encodePassword()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Security/Core/Encoder/PasswordEncoderInterface.php "Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface::encodePassword()") and [isPasswordValid()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Security/Core/Encoder/PasswordEncoderInterface.php "Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface::isPasswordValid()") must first of all make sure the password is not too long, i.e. the password length is no longer than 4096 characters. This is for security reasons (see CVE-2013-5750), and you can use the [isPasswordTooLong()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Security/Core/Encoder/BasePasswordEncoder.php "Symfony\Component\Security\Core\Encoder\BasePasswordEncoder::isPasswordTooLong()") method for this check:

    1. use Symfony\Component\Security\Core\Encoder\BasePasswordEncoder;
    2. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
    3. class FoobarEncoder extends BasePasswordEncoder
    4. {
    5. public function encodePassword($raw, $salt)
    6. {
    7. if ($this->isPasswordTooLong($raw)) {
    8. throw new BadCredentialsException('Invalid password.');
    9. }
    10. // ...
    11. }
    12. public function isPasswordValid($encoded, $raw, $salt)
    13. {
    14. if ($this->isPasswordTooLong($raw)) {
    15. return false;
    16. }
    17. // ...
    18. }
    19. }

Using Password Encoders

When the [getEncoder()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php "Symfony\Component\Security\Core\Encoder\EncoderFactory::getEncoder()") method of the password encoder factory is called with the user object as its first argument, it will return an encoder of type Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface which should be used to encode this user’s password:

  1. // a Acme\Entity\LegacyUser instance
  2. $user = ...;
  3. // the password that was submitted, e.g. when registering
  4. $plainPassword = ...;
  5. $encoder = $encoderFactory->getEncoder($user);
  6. // returns $weakEncoder (see above)
  7. $encodedPassword = $encoder->encodePassword($plainPassword, $user->getSalt());
  8. $user->setPassword($encodedPassword);
  9. // ... save the user

Now, when you want to check if the submitted password (e.g. when trying to log in) is correct, you can use:

  1. // fetch the Acme\Entity\LegacyUser
  2. $user = ...;
  3. // the submitted password, e.g. from the login form
  4. $plainPassword = ...;
  5. $validPassword = $encoder->isPasswordValid(
  6. $user->getPassword(), // the encoded password
  7. $plainPassword, // the submitted password
  8. $user->getSalt()
  9. );

Authentication Events

The security component provides the following authentication events:

NameEvent ConstantArgument Passed to the Listener
security.authentication.successAuthenticationEvents::AUTHENTICATION_SUCCESSSymfony\Component\Security\Core\Event\AuthenticationSuccessEvent
security.authentication.failureAuthenticationEvents::AUTHENTICATION_FAILURESymfony\Component\Security\Core\Event\AuthenticationFailureEvent
security.interactive_loginSecurityEvents::INTERACTIVE_LOGINSymfony\Component\Security\Http\Event\InteractiveLoginEvent
security.switch_userSecurityEvents::SWITCH_USERSymfony\Component\Security\Http\Event\SwitchUserEvent
security.logout_on_changeSymfony\Component\Security\Http\Event\DeauthenticatedEvent::classSymfony\Component\Security\Http\Event\DeauthenticatedEvent

Authentication Success and Failure Events

When a provider authenticates the user, a security.authentication.success event is dispatched. But beware - this event may fire, for example, on every request if you have session-based authentication, if always_authenticate_before_granting is enabled or if token is not authenticated before AccessListener is invoked. See security.interactive_login below if you need to do something when a user actually logs in.

When a provider attempts authentication but fails (i.e. throws an AuthenticationException), a security.authentication.failure event is dispatched. You could listen on the security.authentication.failure event, for example, in order to log failed login attempts.

Security Events

The security.interactive_login event is triggered after a user has actively logged into your website. It is important to distinguish this action from non-interactive authentication methods, such as:

  • authentication based on your session.
  • authentication using a HTTP basic header.

You could listen on the security.interactive_login event, for example, in order to give your user a welcome flash message every time they log in.

The security.switch_user event is triggered every time you activate the switch_user firewall listener.

The Symfony\Component\Security\Http\Event\DeauthenticatedEvent event is triggered when a token has been deauthenticated because of a user change, it can help you doing some clean-up task.

New in version 4.3: The Symfony\Component\Security\Http\Event\DeauthenticatedEvent event was introduced in Symfony 4.3.

See also

For more information on switching users, see How to Impersonate a User.

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