Manually check if password is valid in Symfony

Manually check if password is valid in Symfony

Just using the same encoder, encoding a plain password and matching those two against each other seams the logical solution, but doesn't work as the hash won't be exactly the same depending on the hashing algorithm and salt used.

Let's start with something easier, generating a password without a salt through an encoder:

/** @var EncoderFactoryInterface */
private $encoderFactory;

public function generatePassword(string $plainPassword): string
{
    $encoder = $this->encoderFactory->getEncoder(new User());

    return $encoder->encodePassword($plainPassword, null);
}

Now we use the same encoder to validate the password with a helper class already available:

public function isPasswordValid(string $plainPassword, string $password): bool
{
    $encoder = $this->encoderFactory->getEncoder(new User());

    return $encoder->isPasswordValid($password, $plainPassword, null);
}