How to verify a password on Symfony?
Asked Answered
L

1

6

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();
}
Lowrance answered 3/3, 2022 at 10:0 Comment(2)
You want to change your password if the user enters the old password? Sorry, that's not understandable.Kokura
Ok sorry, i want check old password is correct and set new passwordLowrance
K
13

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.
Kokura answered 3/3, 2022 at 10:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.