根据 Yii2 数据库中的哈希值验证密码

Validate password against hash in database in Yii2

这段代码有什么问题?即使我输入了正确的密码仍然 returns "Old password is incorrect".

我也试过了$hash = Yii::$app->getSecurity->generatePasswordHash($current_password_textbox);

function actionUpdate_password() {
    $current_password_textbox = filter_input(INPUT_POST, 'current_password');
    $new_password = filter_input(INPUT_POST, 'new_password');

    $current_account = \app\models\Users::findOne(yii::$app->user->identity->id);
    $current_hash__from_db = $current_account->password_hash;

    $hash = Yii::$app->getSecurity->generatePasswordHash($current_password_textbox);
    //$hash = Yii::$app->security()->generatePasswordHash($current_password);

    if (Yii::$app->getSecurity()->validatePassword($current_hash__from_db, $hash)) {
        echo " all good, proceed to changing password";
    } else {
        echo "Old password is incorrect";
    }
}

您不应从输入的密码生成哈希。您只需将它传递给 validatePassword() 函数。例如:

$password = 'testpass';
$hash = Yii::$app->getSecurity()->generatePasswordHash($password);
if (Yii::$app->getSecurity()->validatePassword($password, $hash)) {
    echo 'correct password';
} else {
    echo 'incorrect password'
}

在您的案例中,逻辑可能如下所示:

$current_password_textbox = filter_input(INPUT_POST, 'current_password');
$current_account = \app\models\Users::findOne(yii::$app->user->identity->id);   

if (!is_null($currenct_account) && Yii::$app->getSecurity()->validatePassword($current_password_textbox, $current_account->password_hash)) {
    echo " all good, proceed to changing password";
} else {
    echo "Old password is incorrect";
}