- Gii – Generating Module
- Gii – Generating Controller
- Gii – Creating a Model
- Yii - Gii
- Yii - Localization
- Yii - Authorization
- Yii - Authentication
- Yii - Error Handling
- Yii - Logging
- Yii - Aliases
- Yii - Fragment Caching
- Yii - Caching
- Yii - Testing
- Yii - Fields
- Yii - RESTful APIs in Action
- Yii - RESTful APIs
- Yii - Theming
- Yii - Database Migration
- Yii - Active Record
- Yii - Query Builder
- Yii - Data Access Objects
- Yii - Database Access
- Yii - Dependency Injection
- Yii - Configurations
- Yii - Creating a Behavior
- Yii - Behaviors
- Yii - Creating Event
- Yii - Events
- Yii - GridView Widget
- Yii - ListView Widget
- Yii - Data Widgets
- Yii - Data Providers
- Yii - Properties
- Yii - Sorting
- Yii - Pagination
- Yii - Formatting
- Yii - Files Upload
- Yii - Using Cookies
- Yii - Cookies
- Yii - Using Flash Data
- Yii - Sessions
- Yii - AJAX Validation
- Yii - Ad Hoc Validation
- Yii - Validation
- Yii - HTML Forms
- Yii - Rules of URL
- Yii - URL Routing
- Yii - URL Formats
- Yii - Responses
- Yii - HTTP Requests
- Yii - Creating Extensions
- Yii - Extensions
- Yii - Asset Conversion
- Yii - Assets
- Yii - Layouts
- Yii - Views
- Yii - Modules
- Yii - Widgets
- Yii - Models
- Yii - Using Actions
- Yii - Using Controllers
- Yii - Controllers
- Yii - Entry Scripts
- Yii - Application Structure
- Yii - Create Page
- Yii - Installation
- Yii - Overview
- Yii - Home
Yii Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
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 apppcation component.
Implement the yiiwebIdentityInterface interface.
The basic apppcation template comes with a built-in authentication system. It uses the user apppcation 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 vapdation cookieVapdationKey => ymoaYrebZHa8gURuopoHGlK8fLXCKjO , ], cache => [ class => yiicachingFileCache , ], user => [ identityClass => appmodelsUser , enableAutoLogin => true, ], //other components... db => require(__DIR__ . /db.php ), ], modules => [ hello => [ class => appmoduleshelloHello , ], ], params => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for dev environment $config[ bootstrap ][] = debug ; $config[ modules ][ debug ] = [ class => yiidebugModule , ]; $config[ bootstrap ][] = gii ; $config[ modules ][ gii ] = [ class => yiigiiModule , ]; } return $config; ?>
In the above configuration, the identity class for user is configured to be appmodelsUser.
The identity class must implement the yiiwebIdentityInterface 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.
vapdateAuthKey() − Implements the logic for verifying the cookie-based login key.
The User model from the basic apppcation template implements all the above functions. User data is stored in the $users property −
<?php namespace appmodels; class User extends yiiaseObject implements yiiwebIdentityInterface { pubpc $id; pubpc $username; pubpc $password; pubpc $authKey; pubpc $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 */ pubpc static function findIdentity($id) { return isset(self::$users[$id]) ? new static(self::$users[$id]) : null; } /** * @inheritdoc */ pubpc 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 */ pubpc static function findByUsername($username) { foreach (self::$users as $user) { if (strcasecmp($user[ username ], $username) === 0) { return new static($user); } } return null; } /** * @inheritdoc */ pubpc function getId() { return $this->id; } /** * @inheritdoc */ pubpc function getAuthKey() { return $this->authKey; } /** * @inheritdoc */ pubpc function vapdateAuthKey($authKey) { return $this->authKey === $authKey; } /** * Vapdates password * * @param string $password password to vapdate * @return boolean if password provided is vapd for current user */ pubpc function vapdatePassword($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.
Step 2 − Then, add a new function called actionAuth() to the SiteController.
pubpc 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.
Step 4 − To login and logou,t a user you can use the following code.
pubpc 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.
The yiiwebUser class raises the following events −
EVENT_BEFORE_LOGIN − Raised at the beginning of yiiwebUser::login()
EVENT_AFTER_LOGIN − Raised after a successful login
EVENT_BEFORE_LOGOUT − Raised at the beginning of yiiwebUser::logout()
EVENT_AFTER_LOGOUT − Raised after a successful logout