The application’s security starts with two well distinguished phases of the same user login: authentication and authorization.

The first one, authentication, is the process of verifying a user’s identity, usually using a username and password, or email and password, process. Authentication is completed when the user has been recognized and their state has been preserved for further requests.

The second one, authorization, is the process of verifying that the user has the permission to execute a specific action.


Since http requests are stateless, we need to preserve the login status, which means that there is no data context sharing among them. This limit is solved by sessions, mainly files where the web server stores the data. A filename is used as a session identifier and passed to the browser through a cookie or URL parameter of links contained in the HTML response. In this way, the browser keeps the session active by sending the session identifier to the web server through a cookie or a parameter in the request URL, and the web server knows which file contains the session data.

A database table can be used instead of files with the same functionalities.

Yii2 implements authentication through the yiiwebUser component, which manages the user authentication status and also contains a reference to the identityClass that represents the concrete object that we are referring to.

An identityClass class should implement five methods:

  • findIdentity(): This method looks for an instance of an identity class using the ID provided as parameter. It is commonly used when we need to keep the login status via a session.
  • findIdentityByAccessToken(): This one looks for an instance of the identity class using the access token provided by the parameter. It is commonly used when we need to authenticate using a single secret token.
  • getId(): This one returns the ID of the identity instance.
  • getAuthKey(): This method returns the key used to verify the cookie-based login when the login has been completed using a cookie sent by the browser (when Remember me is checked during the login).
  • validateAuthKey(): This method verifies that the provided authKey passed as a parameter is correct (in the cookie-based login).