Yii 认证
验证用户身份的过程称为 验证 。它通常使用用户名和密码来判断用户是否是他自称的用户。
要使用Yii身份验证框架,您需要 -
- 配置用户应用程序组件。
- 实现yii \ web \ IdentityInterface接口。
基本的应用程序模板带有一个内置的认证系统。它使用用户应用程序组件,如下面的代码所示 -
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this
//is required by cookie validation
'cookieValidationKey' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
//other components...
'db' => require(__DIR__ . '/db.php'),
],
'modules' => [
'hello' => [
'class' => 'app\modules\hello\Hello',
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
?>
在上述配置中,用户的身份类别被配置为app \ models \ User。
身份类必须使用以下方法实现 yii \ web \ IdentityInterface -
- findIdentity() - 使用指定的用户标识查找标识类的实例。
- findIdentityByAccessToken() - 使用指定的访问令牌查找身份类的实例。
- getId() - 它返回用户的ID。
- getAuthKey() - 返回用于验证基于Cookie的登录的密钥。
- validateAuthKey() - 实现验证基于cookie的登录密钥的逻辑。
来自基本应用程序模板的用户模型实现了上述所有功能。用户数据存储在 $ users 属性中 -
<?php
namespace app\models;
class User extends \yii\base\Object implements \yii\web\IdentityInterface {
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
private static $users = [
'100' => [
'id' => '100',
'username' => 'admin',
'password' => 'admin',
'authKey' => 'test100key',
'accessToken' => '100-token',
],
'101' => [
'id' => '101',
'username' => 'demo',
'password' => 'demo',
'authKey' => 'test101key',
'accessToken' => '101-token',
],
];
/**
* @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) {
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
}
return null;
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username) {
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* @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 === $password;
}
}
?>
第1步 - 转到URL http:// localhost:8080 / index.php?r =站点/登录, 然后使用admin登录到Web站点以获取登录名和密码。

第2步 - 然后,向 SiteController 添加一个名为 actionAuth() 的新函数。
public function actionAuth(){
// the current user identity. Null if the user is not authenticated.
$identity = Yii::$app->user->identity;
var_dump($identity);
// the ID of the current user. Null if the user not authenticated.
$id = Yii::$app->user->id;
var_dump($id);
// whether the current user is a guest (not authenticated)
$isGuest = Yii::$app->user->isGuest;
var_dump($isGuest);
}
第3步 - 在Web浏览器中输入地址 http:// localhost:8080 / index.php?r = site / auth ,您将看到有关 admin 用户的详细信息。

第4步 - 要登录和登录,用户可以使用以下代码。
public function actionAuth() {
// whether the current user is a guest (not authenticated)
var_dump(Yii::$app->user->isGuest);
// find a user identity with the specified username.
// note that you may want to check the password if needed
$identity = User::findByUsername("admin");
// logs in the user
Yii::$app->user->login($identity);
// whether the current user is a guest (not authenticated)
var_dump(Yii::$app->user->isGuest);
Yii::$app->user->logout();
// whether the current user is a guest (not authenticated)
var_dump(Yii::$app->user->isGuest);
}
首先,我们检查一个用户是否登录。如果该值返回 false ,那么我们通过 Yii :: $ app→user→login() 调用 登录 一个用户,并使用 Yii :: $ app 将他登出 →用户→注销() 方法。
第5步 - 转到URL http:// localhost:8080 / index.php?r = site / auth ,您将看到以下内容。

该 警予\网络\用户 类引发以下事件-
- EVENT_BEFORE_LOGIN - 在 yii \ web \ User :: login() 的开头 引发 __
- EVENT_AFTER_LOGIN - 成功登录后 引发
- EVENT_BEFORE_LOGOUT - 在 yii \ web \ User :: logout() 开始时 引发 __
- EVENT_AFTER_LOGOUT - 成功注销后 引发
下一章:Yii 授权
验证用户是否有足够权限来执行某项操作的过程称为 授权 。Yii提供了一个ACF(访问控制过滤器),一种实现为 yii \ filters \ AccessControl 的授权方法。修改SiteController的behav ...
AI 中文社