php - 通过 RESTful 使用 JSON 格式进行 Yii 用户身份验证

标签 php mysql yii restful-authentication

我希望能够根据数据库中的用户表的电子邮件和密码对 Yii 中的用户进行身份验证。我可以在 Yii 中执行此操作,但现在我希望能够通过 RESTful 使用 JSON 格式对同一用户进行身份验证。下面是我的用于身份验证的 Yii 代码,它位于 Yii 默认的 LoginForm 模型中:

/**
 * Authenticates the password.
 * This is the 'authenticate' validator as declared in rules().
 */
public function authenticate($attribute,$params)
{

    if(!$this->hasErrors())
    {
        $this->_identity=new UserIdentity($this->email,$this->password);
        if(!$this->_identity->authenticate())
            $this->addError('password','Incorrect email or password.');
    }

}

/**
 * Logs in the user using the given email and password in the model.
 * @return boolean whether login is successful
 */
public function login()
{

    if($this->_identity===null)
    {
        $this->_identity=new UserIdentity($this->email,$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;

}

我怎样才能实现这个目标?

最佳答案

此认证基于Cookie/SESSION机制,因此不适用于API查询。我建议您使用带有附加签名参数的查询身份验证。请参阅this reference article 。简而言之,您应该接收用户登录名和密码哈希,使用数据库数据检查它们,然后向客户端返回一些随机生成的 token ,该 token 将用于签署所有其他查询(将此 token 保存到数据库并检查它)。

关于php - 通过 RESTful 使用 JSON 格式进行 Yii 用户身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23177697/

相关文章:

yii - 如何在 YII Active Record 中使用 IN 和 between 子句?

yii - 如何将 yii 1 应用程序转换为版本 2

php - 带有 bool 值的Mysql电子邮件搜索给出错误的值

php - GAE 本地 php - Mint linux - 文件存储不工作

mysqldump : insufficient privileges to show create function 'function name'

jquery - 使用 Yii 在 jQuery 的 $(document).ready 中添加 javascript 的正确方法是什么

php - 无法在 centos 7 中安装 ssh2

php - 数组相同值清除

mysql - 提取 hh :mm:ss from TIMESTAMPDIFF (time, Current_Time())