【问题标题】:Yii2 authenticationYii2认证
【发布时间】:2015-04-14 02:45:08
【问题描述】:

我正在从基本安装修改User.php 模型。

这就是我现在拥有的:

<?php

namespace app\models;

use yii\db\ActiveRecord;

class User extends ActiveRecord implements \yii\web\IdentityInterface
{

    public $id;
    public $username;
    public $password;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return null;
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username]);
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->authKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->password === \Yii::$app->getSecurity()->generatePasswordHash($password);
    }
}

LoginForm.php 正在调用它:

public function getUser()
{
    if ($this->_user === false) {
        $this->_user = User::findByUsername($this->username);
    }

    return $this->_user;
}

我遇到的问题是,当程序到达User.phpvalidatePassword 时,$this-&gt;password 总是null 并且验证失败。

我确信找到了记录,因为我可以看到 LoginForm.php's $this-&gt;_user 中的值。否则,当我试图找到一些随机用户时,它将是 null

如何使用静态函数中找到的填充User.php's $this-&gt;password

【问题讨论】:

    标签: php yii2


    【解决方案1】:

    您没有定义已经存储在用户数据库表中的属性('id'、'username'、'password')。事实上,您在这里用 null 重新定义了您的数据库值。

    还将validatePassword 更改为

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return \Yii::$app->getSecurity()->validatePassword($password, $this->password);
    }
    

    【讨论】:

    • 谢谢。你是对的。我确实尝试删除声明,但删除它们后,$this-&gt;password 不存在。等一下。它确实存在。我先做更多的测试。
    • 酷。那是问题之一。另一个是我使用了错误的验证方法。已更新您的答案以包含该内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多