Events and Event Listeners
Edit this page
During the execution of a Symfony application, lots of event notifications are triggered. Your application can listen to these notifications and respond to them by executing any piece of code.
Symfony triggers several events related to the kernel while processing the HTTP Request. Third-party bundles may also dispatch events, and you can even dispatch custom events from your own code.
All the examples shown in this article use the same KernelEvents::EXCEPTION event for consistency purposes. In your own application, you can use any event and even mix several of them in the same subscriber.
Creating an Event Listener
The most common way to listen to an event is to register an event listener:
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExceptionListener
{
public function __invoke(ExceptionEvent event): void
{
// You get the exception object from the received event
exception = event−>getThrowable();message = sprintf(
'My Error says: %s with code: %s',
exception−>getMessage(),exception->getCode()
);
// Customize your response object to display the exception details
response=newResponse();response->setContent($message);
// HttpExceptionInterface is a special type of exception that
// holds status code and header details
if (exception instanceof HttpExceptionInterface) {
response->setStatusCode(exception−>getStatusCode());response->headers->replace(exception->getHeaders());
} else {
response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
// sends the modified response object to the event
event−>setResponse(response);
}
}
Now that the class is created, you need to register it as a service and notify Symfony that it is an event listener by using a special "tag":
Copy
config/services.yaml
services:
App\EventListener\ExceptionListener:
tags: [kernel.event_listener]
Symfony follows this logic to decide which method to call inside the event listener class:
If the kernel.event_listener tag defines the method attribute, that's the name of the method to be called;
If no method attribute is defined, try to call the __invoke() magic method (which makes event listeners invokable);
If the __invoke() method is not defined either, throw an exception.
There is an optional attribute for the kernel.event_listener tag called priority, which is a positive or negative integer that defaults to 0 and it controls the order in which listeners are executed (the higher the number, the earlier a listener is executed). This is useful when you need to guarantee that one listener is executed before another. The priorities of the internal Symfony listeners usually range from -256 to 256 but your own listeners can use any positive or negative integer.
There is an optional attribute for the kernel.event_listener tag called event which is useful when listener eventargumentisnottyped.Ievent object. For the kernel.exception event, it is ExceptionEvent. Check out the Symfony events reference to see what type of object each event provides.
With this attribute, Symfony follows this logic to decide which method to call inside the event listener class:
If the kernel.event_listener tag defines the method attribute, that's the name of the method to be called;
If no method attribute is defined, try to call the method whose name is on + "PascalCased event name" (e.g. onKernelException() method for the kernel.exception event);
If that method is not defined either, try to call the __invoke() magic method (which makes event listeners invokable);
If the __invoke() method is not defined either, throw an exception.
Defining Event Listeners with PHP Attributes
An alternative way to define an event listener is to use the AsEventListener PHP attribute. This allows to configure the listener inside its class, without having to add any configuration in external files:
Copy
namespace App\EventListener;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
#[AsEventListener]
final class MyListener
{
public function __invoke(CustomEvent $event): void
{
// ...
}
}
You can add multiple #[AsEventListener()] attributes to configure different methods:
Copy
namespace App\EventListener;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
#[AsEventListener(event: CustomEvent::class, method: 'onCustomEvent')]
#[AsEventListener(event: 'foo', priority: 42)]
#[AsEventListener(event: 'bar', method: 'onBarEvent')]
final class MyMultiListener
{
public function onCustomEvent(CustomEvent $event): void
{
// ...
}
public function onFoo(): void
{
// ...
}
public function onBarEvent(): void
{
// ...
}
}
AsEventListener can also be applied to methods directly:
Copy
namespace App\EventListener;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
final class MyMultiListener
{
#[AsEventListener()]
public function onCustomEvent(CustomEvent $event): void
{
// ...
}
#[AsEventListener(event: 'foo', priority: 42)]
public function onFoo(): void
{
// ...
}
#[AsEventListener(event: 'bar')]
public function onBarEvent(): void
{
// ...
}
}
Note that the attribute doesn't require its event parameter to be set if the method already type-hints the expected event.
Creating an Event Subscriber
Another way to listen to events is via an event subscriber, which is a class that defines one or more methods that listen to one or various events. The main difference with the event listeners is that subscribers always know the events to which they are listening.
If different event subscriber methods listen to the same event, their order is defined by the priority parameter. This value is a positive or negative integer which defaults to 0. The higher the number, the earlier the method is called. Priority is aggregated for all listeners and subscribers, so your methods could be called before or after the methods defined in other listeners and subscribers. To learn more about event subscribers, read The EventDispatcher Component.
The following example shows an event subscriber that defines several methods which listen to the same kernel.exception event:
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class ExceptionSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
// return the subscribed events, their methods and priorities
return [
KernelEvents::EXCEPTION => [
['processException', 10],
['logException', 0],
['notifyException', -10],
],
];
}
public function processException(ExceptionEvent $event)
{
// ...
}
public function logException(ExceptionEvent $event)
{
// ...
}
public function notifyException(ExceptionEvent $event)
{
// ...
}
}
That's it! Your services.yaml file should already be setup to load services from the EventSubscriber directory. Symfony takes care of the rest.
If your methods are not called when an exception is thrown, double-check that you're loading services from the EventSubscriber directory and have autoconfigure enabled. You can also manually add the kernel.event_subscriber tag.
Request Events, Checking Types
A single page can make several requests (one main request, and then multiple sub-requests - typically when embedding controllers in templates). For the core Symfony events, you might need to check to see if the event is for a "main" request or a "sub request":
use Symfony\Component\HttpKernel\Event\RequestEvent;
class RequestListener
{
public function onKernelRequest(RequestEvent event)
{
if (!event->isMainRequest()) {
// don't do anything if it's not the main request
return;
}
// ...
}
}
Certain things, like checking information on the real request, may not need to be done on the sub-request
[END CHUNK 1/4]
Reply with OK: [CHUNK x/TOTAL], don't reply anything else, don't explain the text!
Assistant
OK: [CHUNK 1/4]
User
[START CHUNK 2/4]
test.txt
listeners.
Listeners or Subscribers
Listeners and subscribers can be used in the same application indistinctly. The decision to use either of them is usually a matter of personal taste. However, there are some minor advantages for each of them:
Subscribers are easier to reuse because the knowledge of the events is kept in the class rather than in the service definition. This is the reason why Symfony uses subscribers internally;
Listeners are more flexible because bundles can enable or disable each of them conditionally depending on some configuration value.
Event Aliases
When configuring event listeners and subscribers via dependency injection, Symfony's core events can also be referred to by the fully qualified class name (FQCN) of the corresponding event class:
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
class RequestSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
RequestEvent::class => 'onKernelRequest',
];
}
public function onKernelRequest(RequestEvent $event)
{
// ...
}
}
Internally, the event FQCN are treated as aliases for the original event names. Since the mapping already happens when compiling the service container, event listeners and subscribers using FQCN instead of event names will appear under the original event name when inspecting the event dispatcher.
This alias mapping can be extended for custom events by registering the compiler pass AddEventAliasesPass:
Copy
// src/Kernel.php
namespace App;
use App\Event\MyCustomEvent;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\EventDispatcher\DependencyInjection\AddEventAliasesPass;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
protected function build(ContainerBuilder containerBuilder)
{
containerBuilder->addCompilerPass(new AddEventAliasesPass([
MyCustomEvent::class => 'my_custom_event',
]));
}
}
The compiler pass will always extend the existing list of aliases. Because of that, it is safe to register multiple instances of the pass with different configurations.
Debugging Event Listeners
You can find out what listeners are registered in the event dispatcher using the console. To show all events and their listeners, run:
php bin/console debug:event-dispatcher
You can get registered listeners for a particular event by specifying its name:
php bin/console debug:event-dispatcher kernel.exception
or can get everything which partial matches the event name:
Assistant
OK: [CHUNK 2/4]
User
[START CHUNK 3/4]
test.txt
$token);
}
}
Now, configure the subscriber to listen to another event and add onKernelResponse(). This will look for the auth_token flag on the request object and set a custom header on the response if it's found:
Copy
// add the new use statement at the top of your file
use Symfony\Component\HttpKernel\Event\ResponseEvent;
public function onKernelResponse(ResponseEvent event)
{
// check to see if onKernelController marked this as a token "auth'ed" request
if (!token = $event->getRequest()->attributes->get('auth_token')) {
return;
}
response=event->getResponse();
// create a hash and set it as a response header
hash=sha1(response->getContent().response->headers->set('X-CONTENT-HASH', $hash);
}
Assistant
OK: [CHUNK 3/4]
User
[START CHUNK 4/4]
test.txt
configuration).
[END CHUNK 4/4]
Reply with OK: [CHUNK x/TOTAL], don't reply anything else, don't explain the text!
Assistant
OK: [CHUNK 4/4]
User
[START CHUNK 1/3]
test2.txt
Password Hashing and Verification
Edit this page
Most applications use passwords to login users. These passwords should be hashed to securely store them. Symfony's PasswordHasher component provides all utilities to safely hash and verify passwords.
Make sure it is installed by running:
composer require symfony/password-hasher
Configuring a Password Hasher
Before hashing passwords, you must configure a hasher using the password_hashers option. You must configure the hashing algorithm and optionally some algorithm options:
Copy
config/packages/security.yaml
security:
...
password_hashers:
auto hasher with default options for the User class (and children)
App\Entity\User: 'auto'
auto hasher with custom options for all PasswordAuthenticatedUserInterface instances
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
algorithm: 'auto'
cost: 15
In this example, the "auto" algorithm is used. This hasher automatically selects the most secure algorithm available on your system. Combined with password migration, this allows you to always secure passwords in the safest way possible (even when new algorithms are introduced in future PHP releases).
Further in this article, you can find a full reference of all supported algorithms.
Hashing passwords is resource intensive and takes time in order to generate secure password hashes. In general, this makes your password hashing more secure.
In tests however, secure hashes are not important, so you can change the password hasher configuration in test environment to run tests faster:
Copy
config/packages/test/security.yaml
security:
...
password_hashers:
Use your user class name here
App\Entity\User:
algorithm: plaintext # disable hashing (only do this in tests!)
or use the lowest possible values
App\Entity\User:
algorithm: auto # This should be the same value as in config/packages/security.yaml
cost: 4 # Lowest possible value for bcrypt
time_cost: 3 # Lowest possible value for argon
memory_cost: 10 # Lowest possible value for argon
Hashing the Password
After configuring the correct algorithm, you can use the UserPasswordHasherInterface to hash and verify the passwords:
// ...
use
Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class UserController extends AbstractController
{
public function registration(UserPasswordHasherInterface passwordHasher)
{
// ... e.g. get the user data from a registration form
user = new User(...);
$plaintextPassword = ...;
Assistant
OK: [CHUNK 1/3]
User
[START CHUNK 2/3]
test2.txt
UserPasswordHasherInterface
{
// ...
public function needsRehash(string hashed): bool
{
// check whether the current password is hashed using an outdated hasher
hashIsOutdated = ...;
return $hashIsOutdated;
}
}
Dynamic Password Hashers
Usually, the same password hasher is used for all users by configuring it to apply to all instances of a specific class. Another option is to use a "named" hasher and then select which hasher you want to use dynamically.
By default (as shown at the start of the article), the auto algorithm is used for App\Entity\User.
This may be secure enough for a regular user, but what if you want your admins to have a stronger algorithm, for example auto with a higher cost. This can be done with named hashers:
Copy
config/packages/security.yaml
security:
...
password_hashers:
harsh:
algorithm: auto
cost: 15
This creates a hasher named harsh. In order for a User instance to use it, the class must implement PasswordHasherAwareInterface. The interface requires one method - getPasswordHasherName() - which should return the name of the hasher to use:
Copy
// src/Entity/User.php
namespace App\Entity;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherAwareInterface;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class User implements
UserInterface,
PasswordAuthenticatedUserInterface,
PasswordHasherAwareInterface
{
// ...
public function getPasswordHasherName(): ?string
{
if ($this->isAdmin()) {
return 'harsh';
}
return null; // use the default hasher
}
}
When migrating passwords, you don't need to implement PasswordHasherAwareInterface to return the legacy hasher name: Symfony will detect it from your migrate_from configuration.
If you created your own password hasher implementing the PasswordHasherInterface, you must register a service for it in order to use it as a named hasher:
Copy
config/packages/security.yaml
security:
...
password_hashers:
app_hasher:
id: 'App\Security\Hasher\MyCustomPasswordHasher'
This creates a hasher named app_hasher from a service with the ID App\Security\Hasher\MyCustomPasswordHasher.
Supported Algorithms
auto
bcrypt
sodium
PBKDF2
Or create a custom password hasher
The "auto" Hasher
It automatically selects the best available hasher (currently Bcrypt). If PHP or Symfony adds new password hashers in the future, it might select a different hasher.
Because of this, the length of the hashed passwords may change in the future, so make sure to allocate enough space for them to be persisted (varchar(255) should be a good setting).
Assistant
OK: [CHUNK 2/3]
User
[START CHUNK 3/3]
test2.txt
'App\Security\Hasher\MyCustomPasswordHasher'
[END CHUNK 3/3]
Reply with OK: [CHUNK x/TOTAL], don't reply anything else, don't explain the text!
Assistant
OK: [CHUNK 3/3]
User
Résume moi les deux fichiers
Assistant
Le premier fichier, test1.txt, décrit le processus d'installation de Symfony, en partant de la création d'un projet jusqu'à l'ajout de fonctionnalités supplémentaires, telles que la base de données, la console Symfony, le framework de tests PHPUnit, et la configuration de l'environnement de développement.
Le deuxième fichier, test2.txt, décrit comment utiliser la fonctionnalité de hachage de mots de passe de Symfony, en utilisant plusieurs algorithmes de hachage, tels que Bcrypt et Sodium. Il explique également comment créer un hacheur de mots de passe personnalisé en implémentant l'interface PasswordHasherInterface. Le fichier fournit des exemples de configuration de hachage de mots de passe pour différents types d'utilisateurs, ainsi que des instructions pour la migration des anciens mots de passe.
php bin/console debug:event-dispatcher kernel // matches "kernel.exception", "kernel.response" etc.
php bin/console debug:event-dispatcher Security // matches "Symfony\Component\Security\Http\Event\CheckPassportEvent"
The security system uses an event dispatcher per firewall. Use the --dispatcher option to get the registered listeners for a particular event dispatcher:
php bin/console debug:event-dispatcher --dispatcher=security.event_dispatcher.main
How to Set Up Before and After Filters
It is quite common in web application development to need some logic to be performed right before or directly after your controller actions acting as filters or hooks.
Some web frameworks define methods like preExecute() and postExecute(), but there is no such thing in Symfony. The good news is that there is a much better way to interfere with the Request -> Response process using the EventDispatcher component.
Token Validation Example
Imagine that you need to develop an API where some controllers are public but some others are restricted to one or some clients. For these private features, you might provide a token to your clients to identify themselves.
So, before executing your controller action, you need to check if the action is restricted or not. If it is restricted, you need to validate the provided token.
Please note that for simplicity in this recipe, tokens will be defined in config and neither database setup nor authentication via the Security component will be used.
Before Filters with the kernel.controller Event
First, define some token configuration as parameters:
Copy
config/services.yaml
parameters:
tokens:
client1: pass1
client2: pass2
Tag Controllers to Be Checked
A kernel.controller (aka KernelEvents::CONTROLLER) listener gets notified on every request, right before the controller is executed. So, first, you need some way to identify if the controller that matches the request needs token validation.
A clean and easy way is to create an empty interface and make the controllers implement it:
Copy
namespace App\Controller;
interface TokenAuthenticatedController
{
// ...
}
A controller that implements this interface looks like this:
Copy
namespace App\Controller;
use App\Controller\TokenAuthenticatedController;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class FooController extends AbstractController implements TokenAuthenticatedController
{
// An action that needs authentication
public function bar()
{
// ...
}
}
Creating an Event Subscriber
Next, you'll need to create an event subscriber, which will hold the logic that you want to be executed before your controllers. If you're not familiar with event subscribers, you can learn more about them at Events and Event Listeners:
use App\Controller\TokenAuthenticatedController;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class TokenSubscriber implements EventSubscriberInterface
{
public function __construct(
private $tokens
) {
}
public function onKernelController(ControllerEvent event)
{
controller = $event->getController();
// when a controller class defines multiple action methods, the controller
// is returned as [controllerInstance,′methodName′]if(is_array(controller)) {
controller=controller[0];
}
if (controller instanceof TokenAuthenticatedController) {
token = event−>getRequest()−>query−>get(′token′);if(!in_array(token, $this->tokens)) {
throw new AccessDeniedHttpException('This action needs a valid token!');
}
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
}
That's it! Your services.yaml file should already be setup to load services from the EventSubscriber directory. Symfony takes care of the rest. Your TokenSubscriber onKernelController() method will be executed on each request. If the controller that is about to be executed implements TokenAuthenticatedController, token authentication is applied. This lets you have a "before" filter on any controller you want.
If your subscriber is not called on each request, double-check that you're loading services from the EventSubscriber directory and have autoconfigure enabled. You can also manually add the kernel.event_subscriber tag.
After Filters with the kernel.response Event
In addition to having a "hook" that's executed before your controller, you can also add a hook that's executed after your controller. For this example, imagine that you want to add a sha1 hash (with a salt using that token) to all responses that have passed this token authentication.
Another core Symfony event - called kernel.response (aka KernelEvents::RESPONSE) - is notified on every request, but after the controller returns a Response object. To create an "after" listener, create a listener class and register it as a service on this event.
For example, take the TokenSubscriber from the previous example and first record the authentication token inside the request attributes. This will serve as a basic flag that this request underwent token authentication:
Copy
public function onKernelController(ControllerEvent $event)
{
// ...
if (controller instanceof TokenAuthenticatedController) {
token = event−>getRequest()−>query−>get(′token′);if(!in_array(token, $this->tokens)) {
throw new AccessDeniedHttpException('This action needs a valid token!');
}
// mark the request as having passed token authentication
$event->getRequest()->attributes->set('auth_token',
[END CHUNK 2/4]
Reply with OK: [CHUNK x/TOTAL], don't reply anything else, don't explain the text!
token);
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
KernelEvents::RESPONSE => 'onKernelResponse',
];
}
That's it! The TokenSubscriber is now notified before every controller is executed (onKernelController()) and after every controller returns a response (onKernelResponse()). By making specific controllers implement the TokenAuthenticatedController interface, your listener knows which controllers it should take action on. And by storing a value in the request's "attributes" bag, the onKernelResponse() method knows to add the extra header. Have fun!
How to Customize a Method Behavior without Using Inheritance
If you want to do something right before, or directly after a method is called, you can dispatch an event respectively at the beginning or at the end of the method:
Copy
class CustomMailer
{
// ...
public function send(subject,message)
{
// dispatch an event before the method
event=newBeforeSendMailEvent(subject, message);this->dispatcher->dispatch($event, 'mailer.pre_send');
// get subjectandmessage from the event, they may have been modified
subject=event->getSubject();
message=event->getMessage();
// the real method implementation is here
$returnValue = ...;
// do something after the method
event=newAfterSendMailEvent(returnValue);
this−>dispatcher−>dispatch(event, 'mailer.post_send');
return $event->getReturnValue();
}
}
In this example, two events are dispatched:
mailer.pre_send, before the method is called,
and mailer.post_send after the method is called.
Each uses a custom Event class to communicate information to the listeners of the two events. For example, BeforeSendMailEvent might look like this:
class AfterSendMailEvent extends Event
{
public function __construct(
private $returnValue,
) {
}
public function getReturnValue()
{
return $this->returnValue;
}
public function setReturnValue(returnValue)
{
this->returnValue = $returnValue;
}
}
Both events allow you to get some information (e.g. getMessage()) and even change that information (e.g. setMessage()).
Now, you can create an event subscriber to hook into this event. For example, you could listen to the mailer.post_send event and change the method's return value:
use App\Event\AfterSendMailEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class MailPostSendSubscriber implements EventSubscriberInterface
{
public function onMailerPostSend(AfterSendMailEvent event)
{
returnValue = event−>getReturnValue();//modifytheoriginal‘‘returnValue`` value
event−>setReturnValue(returnValue);
}
public static function getSubscribedEvents()
{
return [
'mailer.post_send' => 'onMailerPostSend',
];
}
}
That's it! Your subscriber should be called automatically (or read more about event subscriber
[END CHUNK 3/4]
Reply with OK: [CHUNK x/TOTAL], don't reply anything else, don't explain the text!
// hash the password (based on the security.yaml config for the userclass)hashedPassword = passwordHasher−>hashPassword(user,
plaintextPassword);user->setPassword($hashedPassword);
// ...
}
public function delete(UserPasswordHasherInterface passwordHasher,UserInterfaceuser)
{
// ... e.g. get the password from a "confirm deletion" dialog
$plaintextPassword = ...;
if (!passwordHasher−>isPasswordValid(user, $plaintextPassword)) {
throw new AccessDeniedHttpException();
}
}
}
Reset Password
Using MakerBundle and SymfonyCastsResetPasswordBundle, you can create a secure out of the box solution to handle forgotten passwords. First, install the SymfonyCastsResetPasswordBundle:
composer require symfonycasts/reset-password-bundle
Then, use the make:reset-password command. This asks you a few questions about your app and generates all the files you need! After, you'll see a success message and a list of any other steps you need to do.
php bin/console make:reset-password
You can customize the reset password bundle's behavior by updating the reset_password.yaml file. For more information on the configuration, check out the SymfonyCastsResetPasswordBundle guide.
Password Migration
In order to protect passwords, it is recommended to store them using the latest hash algorithms. This means that if a better hash algorithm is supported on your system, the user's password should be rehashed using the newer algorithm and stored. That's possible with the migrate_from option:
Configure a new Hasher Using "migrate_from"
Upgrade the Password
Optionally, Trigger Password Migration From a Custom Hasher
Configure a new Hasher Using "migrate_from"
When a better hashing algorithm becomes available, you should keep the existing hasher(s), rename it, and then define the new one. Set the migrate_from option on the new hasher to point to the old, legacy hasher(s):
bcrypt # uses the "bcrypt" hasher with the default options
legacy # uses the "legacy" hasher configured above
With this setup:
New users will be hashed with the new algorithm;
Whenever a user logs in whose password is still stored using the old algorithm, Symfony will verify the password with the old algorithm and then rehash and update the password using the new algorithm.
The auto, native, bcrypt and argon hashers automatically enable password migration using the following list of migrate_from algorithms:
PBKDF2 (which uses hash_pbkdf2);
Message digest (which uses hash)
Both use the hash_algorithm setting as the algorithm. It is recommended to use migrate_from instead of hash_algorithm, unless the auto hasher is used.
Upgrade the Password
Upon successful login, the Security system checks whether a better algorithm is available to hash the user's password. If it is, it'll hash the correct password using the new hash. When using a custom authenticator, you must use the PasswordCredentials in the security passport.
You can enable the upgrade behavior by implementing how this newly hashed password should be stored:
When using Doctrine's entity user provider
When using a custom user provider
After this, you're done and passwords are always hashed as securely as possible!
When using the PasswordHasher component outside a Symfony application, you must manually use the PasswordHasherInterface::needsRehash() method to check if a rehash is needed and PasswordHasherInterface::hash() method to rehash the plaintext password using the new algorithm.
Upgrade the Password when using Doctrine
When using the entity user provider, implement PasswordUpgraderInterface in the UserRepository (see the Doctrine docs for information on how to create this class if it's not already created). This interface implements storing the newly created password hash:
// ...
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
class UserRepository extends EntityRepository implements PasswordUpgraderInterface
{
// ...
public function upgradePassword(PasswordAuthenticatedUserInterface user,stringnewHashedPassword): void
{
// set the new hashed password on the User object
user−>setPassword(newHashedPassword);
// execute the queries on the database
$this->getEntityManager()->flush();
}
}
Upgrade the Password when using a Custom User Provider
If you're using a custom user provider, implement the PasswordUpgraderInterface in the user provider:
// ...
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
class UserProvider implements UserProviderInterface, PasswordUpgraderInterface
{
// ...
public function upgradePassword(UserInterface user,stringnewHashedPassword): void
{
// set the new hashed password on the User object
user−>setPassword(newHashedPassword);
// ... store the new password
}
}
Trigger Password Migration From a Custom Hasher
If you're using a custom password hasher, you can trigger the password migration by returning true in the needsRehash() method:
// ...
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class CustomPasswordHasher implements
[END CHUNK 1/3]
Reply with OK: [CHUNK x/TOTAL], don't reply anything else, don't explain the text!
The Bcrypt Password Hasher
It produces hashed passwords with the bcrypt password hashing function. Hashed passwords are 60 characters long, so make sure to allocate enough space for them to be persisted. Also, passwords include the cryptographic salt inside them (it's generated automatically for each new password) so you don't have to deal with it.
Its only configuration option is cost, which is an integer in the range of 4-31 (by default, 13). Each single increment of the cost doubles the time it takes to hash a password. It's designed this way so the password strength can be adapted to the future improvements in computation power.
You can change the cost at any time — even if you already have some passwords hashed using a different cost. New passwords will be hashed using the new cost, while the already hashed ones will be validated using a cost that was used back when they were hashed.
A simple technique to make tests much faster when using BCrypt is to set the cost to 4, which is the minimum value allowed, in the test environment configuration.
The Sodium Password Hasher
It uses the Argon2 key derivation function. Argon2 support was introduced in PHP 7.2 by bundling the libsodium extension.
The hashed passwords are 96 characters long, but due to the hashing requirements saved in the resulting hash this may change in the future, so make sure to allocate enough space for them to be persisted. Also, passwords include the cryptographic salt inside them (it's generated automatically for each new password) so you don't have to deal with it.
The PBKDF2 Hasher
Using the PBKDF2 hasher is no longer recommended since PHP added support for Sodium and BCrypt. Legacy application still using it are encouraged to upgrade to those newer hashing algorithms.
Creating a custom Password Hasher
If you need to create your own, it needs to follow these rules:
The class must implement PasswordHasherInterface (you can also implement LegacyPasswordHasherInterface if your hash algorithm uses a separate salt);
The implementations of hash() and verify() must validate that the password length is no longer than 4096 characters. This is for security reasons (see CVE-2013-5750).
You can use the isPasswordTooLong() method for this check.
use Symfony\Component\PasswordHasher\Exception\InvalidPasswordException;
use Symfony\Component\PasswordHasher\Hasher\CheckPasswordLengthTrait;
use Symfony\Component\PasswordHasher\PasswordHasherInterface;
class CustomVerySecureHasher implements PasswordHasherInterface
{
use CheckPasswordLengthTrait;
public function hash(string plainPassword): string
{
if (this->isPasswordTooLong($plainPassword)) {
throw new InvalidPasswordException();
}
// ... hash the plain password in a secure way
return $hashedPassword;
}
public function verify(string hashedPassword,stringplainPassword): bool
{
if ('' === plainPassword∣∣this->isPasswordTooLong($plainPassword)) {
return false;
}
// ... validate if the password equals the user's password in a secure way
return $passwordIsValid;
}
public function needsRehash(string hashedPassword): bool
{
// Check if a password hash would benefit from rehashing
return needsRehash;
}
}
Now, define a password hasher using the id setting:
Copy
config/packages/security.yaml
security:
...
password_hashers:
app_hasher:
the service ID of your custom hasher (the FQCN using the default services.yaml)
id:
[END CHUNK 2/3]
Reply with OK: [CHUNK x/TOTAL], don't reply anything else, don't explain the text!