How to Choose the Password Encoder Algorithm Dynamically
Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.1 (the current stable version).
Usually, the same password encoder is used for all users by configuring it to apply to all instances of a specific class:
1 2 3 4 5
# app/config/security.yml
security:
# ...
encoders:
Symfony\Component\Security\Core\User\User: sha512
Another option is to use a "named" encoder and then select which encoder you want to use dynamically.
In the previous example, you've set the sha512
algorithm for AppBundle\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 bcrypt
. This can be done with
named encoders:
1 2 3 4 5 6 7
# app/config/security.yml
security:
# ...
encoders:
harsh:
algorithm: bcrypt
cost: 15
Note
If you are running PHP 7.2+ or have the libsodium extension installed, then the recommended hashing algorithm to use is Argon2i.
This creates an encoder named harsh
. In order for a User
instance
to use it, the class must implement
EncoderAwareInterface.
The interface requires one method - getEncoderName()
- which should return
the name of the encoder to use:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity\User;
use Symfony\Component\Security\Core\Encoder\EncoderAwareInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class User implements UserInterface, EncoderAwareInterface
{
public function getEncoderName()
{
if ($this->isAdmin()) {
return 'harsh';
}
return null; // use the default encoder
}
}
If you created your own password encoder implementing the PasswordEncoderInterface, you must register a service for it in order to use it as a named encoder:
1 2 3 4 5 6
# app/config/security.yml
security:
# ...
encoders:
app_encoder:
id: 'app.password_encoder_service'
This creates an encoder named app_encoder
from a service named
app.password_encoder_service
.