I am trying to validate old user password, in order for him to able to change password, but at the moment I am getting Hash is invalid error.
This is validation rule:
['password_old', function($attribute){
if(!$this->validatePassword($this->{$attribute}))
$this->addError($attribute, 'Please Enter Your Old Password');
}],
validatePassword method:
public function validatePassword($password){
return Yii::$app->getSecurity()->validatePassword($this->salt . $password, $this->password);
}
Form used for changing the password:
$form = ActiveForm::begin(
[
'enableAjaxValidation' => true,
'action' => 'user/changepassword',
'id' => 'changePassword'
]
);
echo $form->field($model, 'password_old')->passwordInput( ['autocomplete' => 'off'] );
echo $form->field($model, 'password')->passwordInput(['autocomplete' => 'off'])->label('New Password');
echo $form->field($model, 'password_confirm')->passwordInput(['autocomplete' => 'off']);
Another reason the Hash is invalid error occurs if when you pass a null as the $hash
to the Yii::$app->getSecurity()->validatePassword
method.
I suggest you do a check like this in your code
public function validatePassword($password){
if(is_null($this->password))
return false;
return Yii::$app->getSecurity()->validatePassword($this->salt . $password, $this->password);
}
I'm solved the problem, when change value of password column in DB from varchar(128) to varchar(255) and registerd again.
"Hash is invalid error" because your password is not correct format.
Why?
- When you call validatePassword in a validate rule,
$this->password
is not password stored in database, It is new password - recently submit from your form. To solve problems, you can refer LoginForm
class in yii2-basic-app
or yii-advanced-app
.
Suggestions:
- "Salt" is not necessary because it was included automatically in function
\Yii::$app->security->generatePasswordHash
(PHP 5>= 5.5.0 password_hash
)
I also had this problem and resolved.
The reason is that I used to use the sha1 algorithm before, and after converting it to bcrypt (Yii::$app->security->generatePasswordHash
), I encountered this problem.
My previous password was created with the sha1 algorithm and was in the database.
When I changed the code to the new algorithm and wanted to login, I was wrong.
If you reset the previous password with the new algorithm, the problem is resolved.
You will get this error when the compared password in the database cannot be a hash value!
I get this error when the field value
" $2y$13$TvlDZ5RgBL7Cr1LR9JovfOVEyMwpD6x1dy9sYlngzUIKeuEaqqiry"(first character is a space).
I delete the space character, then it worked.