Yii2 password validation returns fals

I save a model where I fill its password via form, the password hash is generated via $model->setPassword($this->request->post("password_hash"));.

When I try to login, via Yii::$app->security->validatePassword($password, $this->password_hash); it always returns false, no matter if the password variable is the correct password.

Is Yii::$app->security->generatePasswordHash generating an incorrect hash for the password string?

Can you provide the full code for form and controller action and possibly related model code.

At first make sure your input is what you want (like by logging it) (no extra space or something like that )
Yii::info($this->request->post("password_hash"), 'debug_app')

Then it should not be a hash password (I note this because you named it ‘password_hash’)
so you should save the password when you register the user via
Yii::$app->security->generatePasswordHash

Make sure the hashed password saved to db successfully.

Now when user want to login use bellow code to check it
Yii::$app->security->validatePassword($password, $this->password_hash);

If you still has error just send your code here to check it.

1 Like

password_hash is only the name for the field but it comes in plain text.

I had a typo calling request->post: it is Yii::$app->request->post("password_hash") but I put $this->request->post("password_hash").

public function actionCreate() 
{
        $model = new User();

        if ($model->load(Yii::$app->request->post())) {
            $model->setPassword(Yii::$app->request->post("password_hash"));
            $model->generateAuthKey();
            if ($model->save()) {
                Yii::$app->session->setFlash("success", "Usuario registrado correctamente.");
                return $this->redirect(['index']);
            } 
        }

        return $this->render('create', [
            'model' => $model,
        ]);
}

Yii::info($this->request->post("password_hash"), 'debug_app') prints null but, if I drop the line with $model->setPassword(Yii::$app->request->post("password_hash")); the plain password is stored.

While I was writing this answer, I remembered the post model form comes as array ModelForm[field] then, I was having this issue because it.

alright, So you found the problem?
Good luck