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

Yii2中多表验证Identity

2017-08-08 00:00 197 查看
Yii2中自带user identity,在main.php中的components中写入

'user' => [
'identityClass' => 'app\models\User',
]

并在User.php中继承认证接口 <code>yii\web\IdentityInterface</code> 并实现5个方法,5个方法如下:

/**
* 根据给到的ID查询身份。
*
* @param string|integer $id 被查询的ID
* @return IdentityInterface|null 通过ID匹配到的身份对象
*/
public static function findIdentity($id)
{
return static::findOne($id);
}

/**
* 根据 token 查询身份。
*
* @param string $token 被查询的 token
* @return IdentityInterface|null 通过 token 得到的身份对象
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}

/**
* @return int|string 当前用户ID
*/
public function getId()
{
return $this->id;
}

/**
* @return string 当前用户的(cookie)认证密钥
*/
public function getAuthKey()
{
return $this->auth_key;
}

/**
* @param string $authKey
* @return boolean if auth key is valid for current user
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}

根据不同的认证方式(基于cookie的登录验证、基于RESTFul的接口access_token验证或者其他)实现不同的方法,不需要的写入即可实现Yii2中的user Identity。

如果需要实现多个module中的认证且user表不同的时候,只需要在当前module下的Module.php中改写idetityClass即可。
原本想用

$this->setComponents([
'user' => ['identityClass' => 'xxx'],
])

但是不起作用,于是改用

Yii::$app->user->identityClass = 'xxx';

后生效。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Yii2 Module identity