5
votes

In setting up a "change password" feature for a site I have a secondary password entry (where you need to enter your password again before you can change it).

I need to be able to check the user's current password (hashed using Bcrypt) against the password that has been entered.

In my controller action I have:

$currentPassword = $request->request->get('password');
$encoder = $this->container->get('security.password_encoder');
$encodedPassword = $encoder->encodePassword($user, $currentPassword);

if($encodedPassword == $user->getPassword()) { // these don't ever match.
    // ...
}

encodePassword(...) produces a digest of the password that was entered, but it's not the same as the saved password (the plaintext is the same), so I'm thinking that a different salt is being applied and therefore producing the mismatch.

Since Bcrypt incorporates the salt in the password digest, I'm not saving it anywhere.

How can I check if the entered plaintext password matches the stored Bcrypt digest in Symfony 3?

I am not using FOSUserBundle.

1

1 Answers

13
votes

You can compare the $currentPassword password with the stored one using the isPasswordValid method of the encoder service:

$encoderService = $this->container->get('security.password_encoder')

and then pass the user object as first argument of the method:

$match = $encoderService->isPasswordValid($userObject, $currentPassword)

that will returns true if the comparison match or false otherwise.