Yii身份驗證

驗證用戶的身份的過程稱爲驗證。它通常使用的用戶名和密碼來判斷該用戶請求。

要使用 Yii 的認證框架,需要 -

  • 配置用戶應用程序組件

  • 實現 yii\web\IdentityInterface 接口

basic 應用程序模板帶有一個內置的身份驗證系統。

它使用 user 應用程序組件如下面的代碼所示 -

'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' => 'yiibai.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 屬性 -

\[ '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; } } ?>

第1步 - 打開URL=>  http://localhost:8080/index.php?r=site/login 並使用admin的登錄名和密碼登錄到的網站,如下圖所示:
Yii身份驗證

第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步 - 訪問URL地址: http://localhost:8080/index.php?r=site/auth ,將看到有關 admin 用戶的詳細資料:
Yii身份驗證

第4步 - 要登錄和註銷用戶,可參考使用下面的代碼。

public function actionAuth() {
// whether the current user is a guest (not authenticated)
var_dump(Yii::$app->user->isGuest);echo '
';
// 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 '
';
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() 方法來註銷他。

第5步 - 訪問URL: http://localhost:8080/index.php?r=site/auth ,會看到下面的輸出信息:
Yii身份驗證

yii\web\User 類會觸發以下事件 -

  • EVENT_BEFORE_LOGIN − 在  yii\web\User::login() 方法的開始時觸發

  • EVENT_AFTER_LOGIN − 成功登錄後觸發

  • EVENT_BEFORE_LOGOUT − 在 yii\web\User::logout() 方法的開始時觸發

  • EVENT_AFTER_LOGOUT − 成功註銷後觸發