Password hashing in Symfony: hash, store, verify

Password hashing in Symfony: you never store the password, only its hash, computed and checked by the PasswordHasher.

class Employe implements UserInterface, PasswordAuthenticatedUserInterface
{
    #[ORM\Column]
    private ?string $password = null; // the hash, never the password
}

// In ProfilController, once the form is valid:
$employe->setPassword($hasher->hashPassword($employe, $form->get('nouveau')->getData()));
$entityManager->flush();

The algorithm is chosen in security.yaml, under password_hashers; with auto, Symfony picks bcrypt or argon2. UserPasswordHasherInterface provides hashPassword(), and the security:hash-password console command computes a hash to paste into the configuration. At login, the firewall does the checking. Elsewhere, the UserPassword constraint checks the current password in a form. The trap: hashing an input again and comparing it to the stored hash with ===. The salt changes on every call, so the comparison always fails; go through isPasswordValid() or the constraint. And when the hash changes in the database, Symfony closes the other sessions opened with the old password.

The exercises turn the Employe entity into a Symfony user, loaded from the database by their e-mail, whose hiring command hashes the passwords, then build the change-password form: old password checked, new one typed twice and hashed before being saved.

2 exercises work on this concept, by writing code in the browser.

In the tracks