如何在 Symfony 上验证密码?

Mar*_*usz 4 php symfony symfony-security

我想验证用户的现有密码(以允许他们更改密码)。

我想走以下路线,但遇到了散列密码总是显示为不同散列的问题。我在用 UserPasswordHasherInterface

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

if ($hashedOldPassword === $user->getPassword()) {
    setNewPassword();
}
Run Code Online (Sandbox Code Playgroud)

yiv*_*ivi 11

要验证密码,您无需重新哈希它。每次调用时,hashPassword()您都会得到不同的哈希值,因为哈希算法引入了随机以确保安全。

但该接口包含一个更方便的isPasswordValid()方法。

function isPasswordValid(PasswordAuthenticatedUserInterface $user, string $plainPassword): bool
Run Code Online (Sandbox Code Playgroud)

所以简单地做:

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

// no error, let them continue.
Run Code Online (Sandbox Code Playgroud)