验证用户的身份的过程称为验证。它通常使用的用户名和密码来判断该用户请求。
要使用 Yii 的认证框架,需要 -
-
配置用户应用程序组件
- 实现 yii\web\IdentityInterface 接口
basic 应用程序模板带有一个内置的身份验证系统。
它使用 user 应用程序组件如下面的代码所示 -
<?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' => 'xuhuhu.com', ], 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, ], //other components... 'db' => require(__DIR__ . '/db.php'), ], 'modules' => [ 'admin' => [ 'class' => 'app\modules\admin\Admin', ], ], '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。
identity 类必须实现 yii\web\IdentityInterface 接口中方法如下 -
-
findIdentity() − 查找使用指定的用户ID的身份(identity)类的实例
-
findIdentityByAccessToken() − 查找使用指定的访问令牌的身份(identity)类的实例
-
getId() −返回用户ID
-
getAuthKey() − 返回用于验证基于cookie登录的键
-
validateAuthKey() − 实现了验证基于 cookie 登录键的逻辑
从 basic 应用程序模板的 User 模型实现了所有上述功能(models/User.php)。
用户数据被存储在 $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' => 'testuserid100key', 'accessToken' => 'user100-token', ], '101' => [ 'id' => '101', 'username' => 'demo', 'password' => 'demo', 'authKey' => 'testuserid-101key', 'accessToken' => '101-userid-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; } } ?>
第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); }
第4步 - 要登录和注销用户,可参考使用下面的代码。
public function actionAuth() { // whether the current user is a guest (not authenticated) var_dump(Yii::$app->user->isGuest);echo '<br/>'; // 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);echo '<br/>'; 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->user->logout() 方法来注销他。
yii\web\User 类会触发以下事件 -
-
EVENT_BEFORE_LOGIN − 在 yii\web\User::login() 方法的开始时触发
-
EVENT_AFTER_LOGIN − 成功登录后触发
-
EVENT_BEFORE_LOGOUT − 在 yii\web\User::logout() 方法的开始时触发
-
EVENT_AFTER_LOGOUT − 成功注销后触发