通过RESTful和JSON格式进行Yii用户身份验证

时间:2014-04-20 02:11:26

标签: php mysql yii restful-authentication

我希望能够通过电子邮件和密码对Yii中的用户对数据库中的用户表进行身份验证。我可以在Yii中执行此操作,但现在我希望能够通过RESTful with JSON格式对同一用户进行身份验证。下面是我的Yii验证代码,它位于Yii defaut 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;

}

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

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