Yii Framework Login Process Analysis, YII framework process _php Tutorial

Source: Internet
Author: User

Yii Framework Login Process Analysis, YII framework process


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

Yii is a bit difficult for beginners to get started with, especially about Session,cookie and user authentication. Now we are on the login process in Yii, to talk about how to set up Session,cookie and user authentication in the Yii development of some common knowledge

1. Overview

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

All we have to say here is Yii's login process. Using Yii to develop a skeleton of a program using a console tool called Yii Shell gives us the basic structure of developing a Web program in MVC mode and 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, the file is automatically generated, there is a file called Actionlogin. The program login process is never started by default. Yii transfers an address similar to Http://domain.com/index.php?r=site/login to the Actionlogin method described above by calling router components. The functionality of this route is not the focus here. The code for the Actionlogin method is like this.
Copy the 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 whether the user points to the login request (see if there is no post data in the request), if so, first verify the input ($model->validate) and then try to log in ($model->logiin), If all succeeds, jump to the pre-logon page, otherwise the login page is displayed.

3. Framework Login Process

The

LoginForm class inherits from Cformmodel and indirectly inherits from Cmodel, So he offered Cmodel some features like validation and error handling. The login method is the one that performs the validation operation. The method first generates a Useridentity class that represents the user entity, using the user name and password provided by the user. The Authenticate method in this class performs the actual validation actions, such as determining whether the user name and password match from the database. The login method of the LoginForm class determines whether the login succeeds by querying whether authenticate has an error. 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 the login method of Yii::app ()->user->login, or Cwebuser, is the process provided by the YII framework. Let's see what he did. Here is the code for that aspect, located in (Yii) The webauthcwebuser.php file. The
copy Code 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 is set true in order to use cookie-based Authentica tion. ',
Array (' {class} ' =>get_class ($this)));
}
}

The

parameter $identity is the Useridentity class generated at login above, which contains basic user information, such as id,name above, and possibly other custom data getpersistentstates. The program first put the $ The data in the identity is copied to an instance of Cwebuser, which involves generating the corresponding session, in fact, the main purpose is to generate the 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 login. If yes, the cookie is generated (Savetocookie). The
copy Code 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);
}

The first is to create a new Chttpcookie,cookie key via the Getstatekeyprefix method, which returns MD5 (' Yii. ') by default. Get_class ($this). Yii::app ()->getid ()); The ID of the class name and CApplication, which is also a value generated by the CRC32 function. This specific value is of little importance. But each time it produces the same value. Then set the Expire,cookie expiration time, create a new array, contains the basic data, and then the more important is to calculate the value of the cookie, $app->getsecuritymanager ()->hashdata ( Serialize ($data)), getSecurityManager returns an Csecuritymanager object and calls the Hashdata method.
Copy the 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 (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 of the time to generate a validationkey (verification code), and then the verification code and the value of the hash to do some deliberate operation, the final generation of a 40-bit sha1,hash value. The Hashdata method eventually returns the hash value generated by the Computehmac and the string generated by the serialized raw data. There may be doubts about this process. Why do I need a verification code?

Let's take a look at how cookie-based authentication operates. The server generates a cookie after it is sent to the browser and is saved in the browser for a period of time based on the expiration time. Every time a user accesses this website through a browser, the cookie is sent over the HTTP request. This is part of the HTTP protocol, regardless of the language and framework. The server determines whether the user can treat him as a logged-on user by judging the cookie sent. But the cookie is sent by the client browser or even by other programs, This means that the cookie that was sent may have been tampered with. So the server is going through some sort of verification mechanism to determine if it is a cookie that has been sent by itself. This authentication mechanism consists of a hash value in the cookie and the original data that generated the hash value. The server takes out the original data after receiving the cookie , and then the original method to generate a hash value compared to the hash value sent over, if the same, then trust the cookie, otherwise it is definitely illegal request. For example, my Yii website generated 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 generated by the unified Web site. The value of the cookie is two parts, which is a string generated by the Hashdata method. The front part is the hash value, The back is 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 to the back of the original value through the algorithm hash out a value and the pass-through hash value comparison will know is legitimate not trial illegal request. What about the verification code?

If the server is simply to use the back of the original value directly with SHA1 or Md5,hash, then the person sending the request can arbitrarily modify the original value and hash value to pass the server authentication. Because the SHA1 algorithm is public, everyone can use it. So the server needs to be in the hash when a client does not know the verification code to generate a client cannot get the original value of the correct hash hash value (a bit around:)). This is why you need to verify the code. And this verification code must be universal, so the above Getvalidationkey method is to generate a full station unique verification code and save it. By default, the CAPTCHA is a random number and is saved in the (Yii) Runtimestate.bin file. This is the same for each request.

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

It is hoped that this article is helpful to the PHP program design based on YII framework.

http://www.bkjia.com/PHPjc/920980.html www.bkjia.com true http://www.bkjia.com/PHPjc/920980.html techarticle YII Framework Login Process Analysis, YII framework process This paper analyzes the login process of YII framework in detail. Share to everyone for your reference. The specific analysis is as follows: Yii for beginners to get started a bit ...

  • 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.