我是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登录时,我得到了
用户名或密码不正确
我检查了数据库,用户名和密码正确保存在表格中。 对不起,如果我的问题非常愚蠢。任何帮助都会受到欢迎。
谢谢, Mahsa
答案 0 :(得分: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)的使用现在被认为是不安全的。看看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;
}