尝试对用户数据库表进行身份验证时出现 Yii 登录错误


Yii login error when trying to do authentication against a user db table

我在Yii中很新,我正在关注著名的博客教程。但是,我在用户身份验证方面遇到问题。用户身份验证在实现 [IUserIdentity] 接口的类中执行:

class UserIdentity extends CUserIdentity
{
private $_id;
/**
 * Authenticates a user.
 * @return boolean whether authentication succeeds.
 */
public function authenticate()
{
    $user=User::model()->find('LOWER(username)=?',array(strtolower($this->username)));

    if($user===null)
        $this->errorCode=self::ERROR_USERNAME_INVALID;
    else if(!$user->validatePassword($this->password))
        $this->errorCode=self::ERROR_PASSWORD_INVALID;
    else
    {
        $this->_id=$user->id;
        $this->username=$user->username;
        $this->errorCode=self::ERROR_NONE;
    }
    return $this->errorCode==self::ERROR_NONE;
}
/**
 * @return integer the ID of the user record
 */
public function getId()
{
    return $this->_id;
}
}

我没有将纯密码存储在数据库中,而是存储密码的哈希结果和随机生成的盐密钥。在验证用户输入的密码时,我会比较哈希结果。

class User extends CActiveRecord
{  ...
   public function validatePassword($password)
    {
     return $this->hashPassword($password,$this->salt)===$this->password; }
   public function hashPassword($password,$salt)
   {
     return md5($salt.$password); }
}

这是标准的 Yii 登录:

/**
 * Logs in the user using the given username and password in the model.
 * @return boolean whether login is successful
 */
public function login()
{
    if($this->_identity===null)
    {
        $this->_identity=new UserIdentity($this->username,$this->password);
        $this->_identity->authenticate();
    }
    if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
    {
        $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
        Yii::app()->user->login($this->_identity,$duration);
        return true;
    }
    else
        return false;
}

问题是,当我尝试使用 demo/demo 登录时,我得到

用户名或密码不正确

我检查了数据库,用户名和密码是否正确保存在表中。对不起,如果我的问题很愚蠢。任何帮助都将得到赞赏。

谢谢马萨

标准做法是

<?php
function createHash( $password ) {
    $salt = getRandomBytes(8);
    $hash = $salt . hash($salt . $password);
    return $hash; // $hash is what you would store in, for example, your database
}
function checkHash( $password, $hash ) {
    $salt = substr($hash, 0, 8);
    $ok = ($salt . hash($salt . $password) == $hash);
    return $ok;
}

看起来您没有将$salt值附加到哈希结果中。

注意:
如今,md5(和sha1(的使用被认为是不安全的。看看 BCrypt Hash (CRYPT_BLOWFISH( for crypt。

<?php
// Same as above, but will use BCrypt hash (if PHP >= 5.3)
function createHash( $password ) {
    $salt = '$2a$08$'.getRandomBytes(22);
    $hash = crypt($password, $salt);
    return $hash; // $hash is what you would store in, for example, your database
}
function checkHash( $password, $hash ) {
    $ok = (crypt($password, $hash) == $hash);
    return $ok;
}