You are browsing the Symfony 4 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 4 yet, browse the Symfony 3.4 documentation.

How to Manually Encode a Password

4.0 version

How to Manually Encode a PasswordΒΆ

Note

For historical reasons, Symfony uses the term "password encoding" when it should really refer to "password hashing". The "encoders" are in fact cryptographic hash functions.

If, for example, you're storing users in the database, you'll need to encode the users' passwords before inserting them. No matter what algorithm you configure for your user object, the hashed password can always be determined in the following way from a controller:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

public function register(UserPasswordEncoderInterface $encoder)
{
    // whatever *your* User object is
    $user = new App\Entity\User();
    $plainPassword = 'ryanpass';
    $encoded = $encoder->encodePassword($user, $plainPassword);

    $user->setPassword($encoded);
}

In order for this to work, just make sure that you have the encoder for your user class (e.g. App\Entity\User) configured under the encoders key in config/packages/security.yaml.

The $encoder object also has an isPasswordValid() method, which takes the User object as the first argument and the plain password to check as the second argument.

Caution

When you allow a user to submit a plaintext password (e.g. registration form, change password form), you must have validation that guarantees that the password is 4096 characters or fewer. Read more details in How to implement a simple Registration Form.

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