0

我是 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;
}

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

用户名或密码错误

我检查了数据库,用户名和密码正确保存在表中。对不起,如果我的问题很愚蠢。任何帮助将不胜感激。

谢谢,玛莎

4

1 回答 1

3

标准做法是

<?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)被认为是不安全的。查看crypt 的 BCrypt Hash (CRYPT_BLOWFISH)

<?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;
}
于 2012-05-21T11:36:54.070 回答