Yii-authentication

提供:Dev Guides
移動先:案内検索

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;
?>

上記の構成では、ユーザーのIDクラスはapp \ models \ Userに構成されています。

IDクラスは、次のメソッドで yii \ web \ IdentityInterface を実装する必要があります-

  • * findIdentity()*-指定されたユーザーIDを使用してIDクラスのインスタンスを検索します。
  • * findIdentityByAccessToken()*-指定されたアクセストークンを使用してIDクラスのインスタンスを検索します。
  • * 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 = site/login にアクセスし、ログインとパスワードにadminを使用してWebサイトにログインします。

管理者ログイン

ステップ2 *-次に、 actionAuth()*という新しい関数をSiteControllerに追加します。

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 ユーザーに関する詳細情報が表示されます。

actionAuthメソッド

  • ステップ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→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 -ログアウト成功後に発生