An example of _php of YII framework login process

Source: Internet
Author: User

This paper analyzes the login process of the YII framework in detail. Share to everyone for your reference. The specific analysis is as follows:

Yii is a bit difficult for beginners, especially with regard to Session,cookie and user authentication. Now we're going to go through yii login process, and talk about how to set up some common knowledge of Session,cookie and user authentication in YII development

1. Overview

Yii is a fully-stack MVC framework, the so-called full stack refers to the YII framework itself to achieve the web development of all the functions to use, such as Mvc,orm (Dao/activerecord), Globalization (i18n/l10n), caching (caching), Based on JQuery Ajax support (jquery-based Ajax support), role-based user authentication (authentication and role-based access control), program Skeleton Builder ( Scaffolding), inputs validation (input validation), form widgets (widgets), events, Themes (theming), Web Services (Web service), logs (logging), and more. Please refer to the official instructions.

Here is just a yii login process. The development of YII is typically a skeleton of a program using a console tool called a yii shell, which allocates the basic structure for developing web programs in MVC, and is a program that can be run directly. If you know Ruby on rails, the principle is the same.

2. Website Login Process

The generated program has a protected directory, the following controllers directory has a file called sitecontroller.php, this file is automatically generated, which has a file called Actionlogin. program Login process default is always the beginning. Yii transfers addresses such as http://domain.com/index.php?r=site/login through the router component to the Actionlogin method described above. The function of this routing is not the focus of this point. The code for the Actionlogin method is this.

Copy Code code 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 if the user has logged on to the request (see the request for post data), if so, first validate the input ($model->validate) and then try to log in ($model->logiin), If all succeeds, jump to the page before the login, otherwise the login page will be displayed.

3. Framework Login Process

The LoginForm class inherits from the Cformmodel, indirectly inherits from the Cmodel, So he provides Cmodel provides some features like validation and error handling. The login method is to perform the validation operation. Method first generates a Useridentity class that represents a user entity by user-supplied username and password. The Authenticate method in this class performs the actual validation action, such as determining whether the user name and password match from the database. The login method of the LoginForm class determines whether a login is successful by querying the authenticate for errors. If successful, execute the Yii::app ()->user->login method to enable the user to actually log on to the system. These processes are provided by the user program, and Yii::app ()->user->login is the Cwebuser login method that is the process provided by the YII framework. Let's see what he's done. Here is the code for that area, located in (Yii) webauthcwebuser.php file.

Copy Code code 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 with the ' ", cookie-based. ')
Array (' {class} ' =>get_class ($this)));
}
}

Parameter $identity is the Useridentity class that is generated at login, which contains basic user information, such as the id,name above, and possibly other custom data getpersistentstates. The program first copies the data in the $identity to the Cwebuser instance, which includes generating the corresponding session, in fact, the main purpose is to generate session. Then according to the parameter $duration (the time the cookie was saved) and the Allowautologin property to determine whether to generate a cookie that can be used for the next automatic logon. If so, generate a cookie (Savetocookie).

Copy Code code 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, a new Chttpcookie,cookie key is obtained by Getstatekeyprefix method, which returns MD5 (' Yii. ') by default. Get_class ($this). Yii::app ()->getid ()), which is the ID of the class name and CApplication, which is also a value generated by the CRC32 function. It doesn't matter how much this particular value is. But each time it produces the same value. Then set the expiration time of the Expire,cookie, then create a new array, containing the basic data, then it is more important to compute the value of the cookie, $app->getsecuritymanager ()->hashdata ( Serialize ($data)), getSecurityManager returns an Csecuritymanager object and invokes the Hashdata method.

Copy Code code 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), Chr (0));
Return $func (Str_repeat (Chr 0x5c) ^ substr ($key, 0,)). Pack ($pack, $func (Str_repeat (Chr (0x36),) ^ substr ($ke Y, 0, 64)). $data)));
}

Hashdata calls the Computhmac method to generate a hash value. Hash algorithm has SHA1 and MD5 two kinds, the default is to use SHA1.  Hash time also to generate a validationkey (authentication code), and then the verification code and the value of the hash to do some deliberately scheduled operations, the final generation of a 40-bit sha1,hash value. The Hashdata method ultimately returns the hash value generated by the COMPUTEHMAC and the serialized raw data-generated string. There may be questions about this process. If so, why do I need a captcha?

Let's take a look at how the cookie-based validation is done. The server generates a cookie and is saved in the browser for a period of time, depending on the expiration time. The user sends the cookie to the Web site each time it is accessed through the browser. This is part of the HTTP protocol, independent of language and framework. The server determines whether the user can treat him as a logged-on user by judging the cookie sent over. But cookies are from the client browser or even other programs, In other words, the cookie that was sent over may have been tampered with. So the server is going to use some sort of validation mechanism to determine if it's a cookie that was later sent by itself. The authentication mechanism is to include a hash value in the cookie and the raw data that generated the hash value. The server receives the cookie and then extracts the original data , and then generate a hash value in the original method to compare with the hash value sent over, if the same, then trust the cookie, otherwise it is an illegal request. For example, my Yii Web site generates such a cookie:

Cookie name:b72e8610f8decd39683f245d41394b56

Cookie value:1cbb64bdea3e92c4ab5d5cb16a67637158563114a%3a4%3a%7bi%3a0%3bs%3a7%3a%22maxwell%22%3bi%3a1%3bs%3a7% 3a%22maxwell%22%3bi%3a2%3bi%3a3600%3bi%3a3%3ba%3a2%3a%7bs%3a8%3a%22realname%22%3bs%3a6%3a%22helloc%22%3bs%3a4% 3a%22myid%22%3bi%3a123%3b%7d%7d

The cookie name is a MD5 value that the Web site generates uniformly. Cookie value is two parts, which is a string generated by the Hashdata method. The previous part is a hash value, followed by the original value. That is, the previous 1cbb64bdea3e92c4ab5d5cb16a67637158563114 is a hash value, followed by the original value. This hash value is a 40-bit string generated with SHA1. The server put the original value of the following algorithm hash out a value and this pass over the hash value comparison is known to be legal not to audit illegal request. What about the verification code?

If the server simply put the original value of the following directly with SHA1 or Md5,hash, the person who sent the request could modify the original value and hash value at will to authenticate with the server. Because the SHA1 algorithm is public, everyone can use it. Therefore, the server needs to add a client does not know at the time of the verification code to generate a client can not get the original value of the hash of the hash value (a bit around:). That's why you need to verify the code. And this verification code must be universal, so the Getvalidationkey method above is to generate a whole station unique verification code and save it. By default, the CAPTCHA is a random number and is saved in (YII) Runtimestate.bin file. This is the same for every request.

The end of the login process is to send the generated cookie to the browser. The next request can be used for verification.

I hope this article will help you with the PHP program design 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.