Yii身份驗證


驗證使用者的身份的過程稱為驗證。它通常使用的使用者名和密碼來判斷該使用者請求。
要使用 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' => 'tw511.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;
      }
   }
?>
第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 使用者的詳細資料:

第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() 方法來登出他。
第5步 - 存取URL:http://localhost:8080/index.php?r=site/auth ,會看到下面的輸出資訊:

yii\web\User 類會觸發以下事件 -
  • EVENT_BEFORE_LOGIN ? 在  yii\web\User::login() 方法的開始時觸發

  • EVENT_AFTER_LOGIN ? 成功登入後觸發

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

  • EVENT_AFTER_LOGOUT ? 成功登出後觸發