How to verify a password on Symfony?

4.8k Views Asked by At

I want verify the existing password for a user (to allow them to change their password).

I thought to go the following route but ran into the problem that the hashed password always shows up as a different hash. I am using UserPasswordHasherInterface.

$hashedOldPassword = $passwordHasher->hashPassword(
        $user,
        $data['oldPassword']
    );

if ($hashedOldPassword === $user->getPassword()) {
    setNewPassword();
}
1

There are 1 best solutions below

0
yivi On

To verify a password you do not rehash it. Each time you call hashPassword() you'll get a different hash, because the hashing algorithm introduces a random salt for security.

But that interface includes a much more convenient isPasswordValid() method.

function isPasswordValid(PasswordAuthenticatedUserInterface $user, string $plainPassword): bool

So simply do:

if (!$passwordHasher->isPasswordValid($user, $oldPassword)) {
   // error, you can't change your password 
   // throw exception or return, etc.
}

// no error, let them continue.