2012-05-21 43 views
0

我在Yii中很新,我正在關注着名的博客教程。但是,我遇到了用戶身份驗證問題。用戶認證在執行[IUserIdentity]接口的類進行:Yii登錄錯誤,當試圖對用戶db表進行身份驗證時

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

的問題是,當我嘗試與演示/演示登錄,我得到

錯誤的用戶名或密碼

我檢查了數據庫a nd用戶名和密碼正確保存在表中。 對不起,如果我的問題是非常愚蠢的。任何幫助將是令人滿意的。

感謝, Mahsa

+0

目前看起來很好。檢查什麼是'UserIdentity :: errorCode'。你是否在創建新用戶時以及何時檢查身份驗證時使用相同的鹽? –

+0

你能解釋一下我可以如何檢查它是否使用相同的鹽嗎? –

+0

你的數據庫中保存了什麼作爲密碼? MD5($鹽。$密碼)?你在哪裏鹽?在模型中硬編碼或保存在數據庫中? –

回答

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; 
} 
相關問題