您的位置:首页 > 编程语言 > PHP开发

Yii框架官方指南系列42——专题:验证和授权(Authentication and Authorization)

2014-11-07 00:00 573 查看
对于需要限制某些用户访问的网页,我们需要使用验证(Authentication)和授权(Authorization)。 验证是指核查一个人是否真的是他自己所声称的那个人。这通常需要一个用户名和密码, 但也包括任何其他可以表明身份的方式,例如一个智能卡,指纹等等。 授权则是找出已通过验证的用户是否允许操作特定的资源。 这一般是通过查询此用户是否属于一个有权访问该资源的角色来判断的。

Yii 有一个内置的验证/授权(auth)框架,用起来很方便,还能对其进行自定义,使其符合特殊的需求。

Yii auth 框架的核心是一个预定义的 用户(user)应用组件 它是一个实现了 IWebUser 接口的对象。 此用户组件代表当前用户的持久性认证信息。我们可以通过Yii::app()->user在任何地方访问它。

使用此用户组件,我们可以通过 CWebUser::isGuest 检查检查一个用户是否登陆; 可以 登录(login) 或 注销(logout) 一个用户;我们可以通过CWebUser::checkAccess检查此用户是否可以执行特定的操作;还可以获取此用户的唯一标识(unique identifier)及其他持久性身份信息。

1. 定义身份类 (Defining Identity Class)

为了验证一个用户,我们定义一个有验证逻辑的身份类。这个身份类实现IUserIdentity 接口。

不同的类可能实现不同的验证方式(例如:OpenID,LDAP)。最好是继承 CUserIdentity,此类是居于用户名和密码的验证方式。

定义身份类的主要工作是实现IUserIdentity::authenticate方法。在用户会话中根据需要,身份类可能需要定义别的身份信息

应用实例

下面的例子,我们使用Active Record来验证提供的用户名、密码和数据库的用户表是否吻合。我们通过重写getId函数来返回验证过程中获得的_id变量(缺省的实现则是返回用户名)。在验证过程中,我们还借助CBaseUserIdentity::setState函数把获得的title信息存成一个状态。
The implementation of the authenticate() to use the database to validate credentials.
Overriding the CUserIdentity::getId() method to return the _id property because the default implementation returns the username as the ID.
Using the setState() (CBaseUserIdentity::setState) method to demonstrate storing other information that can easily be retrieved upon subsequent requests.
class UserIdentity extends CUserIdentity
{
    private $_id;
    public function authenticate()
    {
        $record=User::model()->findByAttributes(array('username'=>$this->username));
        if($record===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        else if($record->password!==md5($this->password))
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else
        {
            $this->_id=$record->id;
            $this->setState('title', $record->title);
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
    }

    public function getId()
    {
        return $this->_id;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: