问题
This is my validatePassword function in models/user.php
public function validatePassword($password)
{
/* var_dump(Yii::$app->getSecurity()->validatePassword($password, $this->password)); */
return Yii::$app->getSecurity()->validatePassword($password, $this->password);
};
this is my setPassword function in models/user.php
public function setPassword($password)
{
$this->password = Yii::$app->getSecurity()->generatePasswordHash($password);
}
to call setPassword function I use following beforeSave function in models/user.php:
public function beforeSave($insert) {
$this->setPassword($this->password);
$this->generateAuthKey();
$this->generatePasswordResetToken();
return true;
}
model rules models/user.php
public function rules()
{
return [
[['username', 'password', 'role'], 'required'],
[['username', 'password'], 'string', 'max' => 45],
[['role'], 'string', 'max' => 16],
[['auth_key'], 'string', 'max' => 32],
[['password_reset_token'], 'string', 'max' => 255],
[['username'], 'unique']
];
}
Why is the validation of my password always false?
回答1:
I think you made a mistake in the database. Perhaps, your password field has VARCHAR(32) (you wrote "it's normal when i used md5 password.").
Yii::$app->getSecurity()->generatePasswordHash($password);
This function generates the string is longer than 32 characters. For the password field, use the TEXT instead of VARCHAR(32).
回答2:
maybe you can see how to login in yii2 on http://www.bsourcecode.com/yiiframework2/yii-2-user-login-from-database/ or another stackoverflow question Yii Framework 2.0 Login With User Database
hope could help you..
回答3:
Is $this->password equal with db value when validatePassword performing?
I believe setPassword() worked for $this->password before validatePassword.
来源:https://stackoverflow.com/questions/29163843/validate-password-for-login-always-false-using-yii-2