Yii Tutorial on Yii Authentication

the process of verifying the identity of a user is called authentication. it usually uses a username and a password to judge whether the user is one who he claims as.

to use the yii authentication framework, you need to −

  • configure the user application component.
  • implement the yii\web\identityinterface interface.

the basic application template comes with a built-in authentication system. it uses the user application component as shown in the following code −

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

in the above configuration, the identity class for user is configured to be app\models\user.

the identity class must implement the yii\web\identityinterface with the following methods −

  • findidentity() − looks for an instance of the identity class using the specified user id.

  • findidentitybyaccesstoken() − looks for an instance of the identity class using the specified access token.

  • getid() − it returns the id of the user.

  • getauthkey() − returns a key used to verify cookie-based login.

  • validateauthkey() − implements the logic for verifying the cookie-based login key.

the user model from the basic application template implements all the above functions. user data is stored in the $users property −

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

step 1 − go to the url http://localhost:8080/index.php?r=site/login and log in into the web site using admin for a login and a password.

admin login

step 2 − then, add a new function called actionauth() to the 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);
}

step 3 − type the address http://localhost:8080/index.php?r=site/auth in the web browser, you will see the detailed information about admin user.

actionauth method

step 4 − to login and logou,t a user you can use the following code.

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);
}

at first, we check whether a user is logged in. if the value returns false, then we log in a user via the yii::$app → user → login() call, and log him out using the yii::$app → user → logout() method.

step 5 − go to the url http://localhost:8080/index.php?r=site/auth, you will see the following.

verifying user login

the yii\web\user class raises the following events −

  • event_before_login − raised at the beginning of yii\web\user::login()

  • event_after_login − raised after a successful login

  • event_before_logout − raised at the beginning of yii\web\user::logout()

  • event_after_logout − raised after a successful logout