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

問題は、demo / demoでログインしようとすると、

ユーザーネームまたはパスワードが違います

データベースを確認しましたが、ユーザー名とパスワードがテーブルに正しく保存されています。私の質問が非常に愚かであるならば申し訳ありません。どんな助けでも感謝されます。

ありがとう、Mahsa

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ハッシュ(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 に答える