驗證用戶的身份的過程稱為驗證。它通常使用的用戶名和密碼來判斷該用戶請求。
要使用 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 − 成功註銷後觸發



