Yii Framework logon process analysis

Source: Internet
Author: User
Tags hmac ruby on rails
This article mainly introduces the logon process of the Yii Framework, analyzes in detail the principles of the Yii Framework and detailed logon processes, and helps you to gain an in-depth understanding of the principles of the Yii Framework, if you need it, you can refer to this article to analyze the logon process of the Yii Framework in detail. Share it with you for your reference. The specific analysis is as follows:

Yii is a bit difficult for new users, especially for session, cookie, and user verification. Now let's talk about how to set session, cookie, and user verification in Yii development.

1. Overview

Yii is a full-stack MVC framework. The so-called full-stack architecture refers to the Yii Framework itself implementing all the functions required for web development, such as MVC, ORM (DAO/ActiveRecord), Globalization (I18N/L10N), cache (caching), jQuery-based Ajax support ), role-based authentication and role-based access control, scaffolding, input validation, and form widgets ), events, theming, web services, and logging. for more information, see official instructions.

Here we only talk about the logon process of Yii. yii development is generally used to generate a skeleton of a program using a console tool called Yii shell, which assigns us the basic structure for developing web programs in MVC mode, it is a program that can be run directly. if you know Ruby on Rails, the principle is the same.

2. website logon process

The generated program has a protected directory, and the following controllers Directory has a directory named SiteController. php file, which is automatically generated, contains a file called actionLogin. the program logon process starts from the beginning by default. yii put like a http://domain.com/index.php? The r = site/login address is transferred to the above-mentioned actionLogin method by calling the router component. this routing function is not the focus here. the code of the actionLogin method is as follows.

The code is as follows:

Public function actionLogin (){
$ Model = new LoginForm;
// Collect user input data
If (isset ($ _ POST ['loginform']) {
$ Model-> attributes = $ _ POST ['loginform'];
// Validate user input and redirect to the previous page if valid
If ($ model-> validate () & $ model-> login ())
$ This-> redirect (Yii: app ()-> user-> returnUrl );
}
// Display the login form
$ This-> render ('login', array ('model' => $ model ));
}

First initialize a LoginForm class, and then determine whether the user has clicked the login request (check whether there is POST data in the request). If yes, verify the input ($ model-> validate) first) then try to log on ($ model-> logiin). if both are successful, you will jump to the page before logon. Otherwise, the logon page will be displayed.

3. framework logon process

The LoginForm class inherits from CFormModel and is indirectly inherited from CModel. Therefore, it provides functions such as verification and error handling. the login method is used for verification. the method first generates a UserIdentity class that represents the user entity through the user name and password provided by the user. the authenticate method in this class performs the actual verification action, for example, judging from the database whether the user name and password match. the login method of the LoginForm class checks whether the logon is successful by querying whether an error occurs in authenticate. if the logon succeeds, run the Yii: app ()-> user-> login method to log on to the system. the preceding processes are provided by the user program, and the Yii: app ()-> user-> login (that is, the CWebUser login method) is the process provided by the Yii Framework. let's see what he did. the following is the code in this aspect, which is located at (Yii) webauthCWebUser. php file.

The code is as follows:

Public function login ($ identity, $ duration = 0 ){
$ This-> changeIdentity ($ identity-> getId (), $ identity-> getName (), $ identity-> getPersistentStates ());
If ($ duration> 0 ){
If ($ this-> allowAutoLogin)
$ This-> saveToCookie ($ duration );
Else
Throw new CException (Yii: t ('yii', '{class}. allowAutoLogin must be set true in order to use cookie-based authentication .',
Array ('{class}' => get_class ($ this ))));
}
}

The $ identity parameter is the UserIdentity class generated during logon. it contains basic user information, such as the Id, Name, and other custom data getPersistentStates. the program first copies the data in $ identity to the CWebUser instance. This process includes generating the corresponding session. In fact, the main purpose is to generate the session. then, based on the $ duration parameter (cookie storage time) and allowAutoLogin attribute, determine whether to generate a cookie that can be used for next automatic login. if yes, a cookie (saveToCookie) is generated ).

The code is as follows:

Protected function saveToCookie ($ duration ){
$ App = Yii: app ();
$ Cookie = $ this-> createIdentityCookie ($ this-> getStateKeyPrefix ());
$ Cookie-> expire = time () + $ duration;
$ Data = array (
$ This-> getId (),
$ This-> getName (),
$ Duration,
$ This-> saveIdentityStates (),
);
$ Cookie-> value = $ app-> getSecurityManager ()-> hashData (serialize ($ data ));
$ App-> getRequest ()-> getCookies ()-> add ($ cookie-> name, $ cookie );
}

First, create a CHttpCookie. the cookie key is obtained using the getStateKeyPrefix method. by default, md5 ('yii. '. get_class ($ this ). '. '. yii: app ()-> getId (); that is, the class name and CApplication Id. this Id is a value generated by the crc32 function. the specific value is irrelevant. however, the same value is generated every time. next, set the expiration time of the expire and cookie, and create a new array containing the basic data. Next, calculate the cookie value, $ app-> getSecurityManager () -> hashData (serialize ($ data), getSecurityManager returns a CSecurityManager object and calls the hashData method.

The code is as follows:

Public function hashData ($ data ){
$ Hmac = $ this-> computeHMAC ($ data );
Return $ hmac. $ data;
}

Protected function computeHMAC ($ data ){
If ($ this-> _ validation === 'sha1 '){
$ Pack = 'h40 ';
$ Func = 'sha1 ';
}
Else {
$ Pack = 'h32 ';
$ Func = 'md5 ';
}
$ Key = $ this-> getValidationKey ();
$ Key = str_pad ($ func ($ key), 64, chr (0 ));
Return $ func (str_repeat (chr (0x5C), 64) ^ substr ($ key, 0, 64 )). pack ($ pack, $ func (str_repeat (chr (0x36), 64) ^ substr ($ key, 0, 64 )). $ data )));
}

HashData calls the computHMAC method to generate a hash value. hash algorithms include SHA1 and MD5. SHA1 is used by default. during the hash operation, a validationKey (verification code) is generated. then, the verification code and the value to be hash are deliberately calculated to generate a 40-bit SHA1 and hash value. the hashData method returns the hash value generated by computeHMAC and the string generated by serialized raw data. this process may have doubts. why do I need a verification code?

Let's take a look at how cookie-based authentication is performed. the server generates a cookie and sends it to the browser. the cookie is saved in the browser for a period of time based on the Expiration Time. each time a user accesses the website through a browser, the cookie is sent along with the HTTP request. this is part of the http protocol and has nothing to do with the language and framework. the server determines whether the user can regard the cookie as a logged-on user. however, the cookie is sent from the client browser or other programs. that is to say, the sent cookie may have been tampered. therefore, the server must use a validation mechanism to determine whether the cookie is sent by itself. the authentication mechanism is to include a hash value in the cookie and the original data that generates the hash value. after receiving the cookie, the server retrieves the original data and generates a hash value based on the original method to compare the hash value. if the hash value is the same, the server trusts the cookie. Otherwise, the request is definitely invalid. for example, my Yii website generates such a cookie:

Cookie name: b72e8610f8decd3863f245d41394b56

Cookie value: %3a4% 3A % 7Bi % 3A0% 3Bs % 3A7% 3A % 22 maxwell % 22% 3Bi % 3A1% 3Bs % 3A7% 3A % 22 maxwell % 22% 3Bi % 3A2% 3Bi % 3A3600% 3Bi % 3A3% 3Ba % 3A2% 3A % 7Bs % 3A8% 3A % 22 realname % 22% 3Bs % 3A6% 3A % 22 helloc % 22% 3Bs % 3A4% 3A % 22 myId % 22% 3Bi % 3A123% 3B % 7D % 7D

Cookie name is a uniform md5 value generated by the website. the cookie value is a string generated by the hashData method. the first part is the hash value, followed by the original value. that is to say, the previous 1cbb64bdea3e92c4ab5d5cb16a67637158563114 is the hash value, followed by the original value. the hash value is a 40-bit string generated using SHA1. the server uses the algorithm to hash the original values and compares them with the hash values. This means that the request is legal and illegal. what about the verification code?

If the server simply uses SHA1 or MD5 or hash for the subsequent original values, the sender of the request can modify the original value and hash value at will to pass the server verification. because the SHA1 algorithm is public, everyone can use it. therefore, the server needs to add a verification code unknown to the client during hash to generate a hash value (a bit around :) that cannot be obtained through the original hash value :)). this is why the verification code is required. the verification code must be universal throughout the site. Therefore, the getValidationKey method above generates and saves a unique verification code for the entire site. by default, the verification code is a random number and saved in (yii) runtimestate. binfile. this is the same for every request.

At the end of the login process, the generated cookie is sent to the browser. the next request can be used for verification.

I hope this article will help you design PHP programs based on the Yii Framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.