In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you the example analysis of the login process of the Yii framework, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
The specific analysis is as follows:
Yii is a bit difficult for beginners, especially when it comes to session,cookie and user authentication. Now let's talk about the login process in Yii to talk about some general knowledge of how to set up session,cookie and user authentication in Yii development.
1. Overview
Yii is a full-stack MVC framework, which means that the Yii framework itself implements all the functions needed in web development, such as MVC,ORM (DAO/ActiveRecord), I18N/L10N (I18N/L10N), caching (cache), jQuery Ajax-based support (jQuery-based AJAX support), role-based user authentication (authentication and role-based access control), program skeleton generator (scaffolding), input verification (input validation). Form widget (widgets), event (events), topic (theming), web service (Web services), log (logging) and other functions. See the official instructions for details.
What I want to talk about here is only the login process of Yii. Developing with Yii generally uses a console tool called Yii shell to generate the skeleton of a program, which assigns us the basic structure of developing web programs according to MVC, and is a program that can be run directly. If you know Ruby on Rails, the principle is the same.
two。 Website login process
There is a protected directory in the generated program, and there is a file called SiteController.php in the controllers directory below. This file is automatically generated, and there is a file called actionLogin. The program login process starts from the beginning by default. Yii transfers addresses like http://domain.com/index.php?r=site/login to the actionLogin method mentioned above through a component called router. The function of this route is not the point here. The code of the actionLogin method is like this.
Public function actionLogin () {$model=new LoginForm;// collect user input dataif (isset ($_ POST ['LoginForm'])) {$model- > attributes=$_POST [' LoginForm']; / / validate user input and redirect to the previous page if validif ($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 clicked on the login request (to see if there is any POST data in the request). If so, verify the input ($model- > validate) and then try to log in ($model- > logiin). If both are successful, jump to the pre-login page, otherwise the login page is displayed.
3. Framework login process
The LoginForm class inherits from CFormModel and indirectly from CModel, so it provides CModel with some functions such as validation and error handling. The login method performs the verification operation. The method first generates a UserIdentity class to represent the user entity through the user name and password provided by the user. The authenticate method in this class performs the actual authentication action, such as judging whether the user name and password match from the database. The login method of the LoginForm class determines whether the login is successful by querying authenticate for errors. If successful, execute the Yii::app ()-> user- > login method to make the user actually log in to the system. The processes mentioned above are provided by the user program, and Yii::app ()-> user- > login, that is, the login method of CWebUser is the process provided by the Yii framework. Let's see what he has done. The following is the code for this aspect, located in the (Yii) webauthCWebUser.php file.
Public function login ($identity,$duration=0) {$this- > changeIdentity ($identity- > getId (), $identity- > getName (), $identity- > getPersistentStates ()); if ($duration > 0) {if ($this- > allowAutoLogin) $this- > saveToCookie ($duration); elsethrow new CException (Yii::t ('yii',' {class} .allowAutoLogin must be set true in order to use cookie-based authentication.',array (' {class}'= > get_class ($this);}}
The parameter $identity is the UserIdentity class generated when logging in above, which contains basic user information, such as Id,Name above, and possibly other custom data getPersistentStates. The program first copies the data in $identity to the instance of CWebUser. This process includes generating the corresponding session. In fact, the main purpose is to generate session. Then use the parameter $duration (time cookie saved) and the allowAutoLogin property to determine whether to generate a cookie that can be used to log in automatically next time. If so, cookie (saveToCookie) is generated.
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, the key of a new CHttpCookie,cookie is obtained through the getStateKeyPrefix method, which returns md5 by default ('Yii.'.get_class ($this).'. Yii::app ()-> getId ()); that is, the class name and the Id of CApplication, which is a value generated by the crc32 function. It doesn't matter what the specific value is. But it produces the same value every time. Then set the expiration time of expire,cookie, and then create a new array, which contains the basic data. Then it is more important to calculate the value of cookie, $app- > getSecurityManager ()-> hashData (serialize ($data)). GetSecurityManager returns an object of CSecurityManager and calls the hashData method.
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 algorithm has two kinds of SHA1 and MD5, the default is to use SHA1. Hash also generates a validationKey (CAPTCHA), and then performs some deliberately arranged operations between the CAPTCHA and the value to be hash, and finally generates a 40-bit SHA1, hash value. The hashData method finally returns the hash value generated by computeHMAC and the string generated by the serialized raw data. There may be doubts about this process. For example, why should there be a CAPTCHA?
Let's first take a look at how cookie-based authentication works. The server generates a cookie and sends it to the browser and saves it in the browser for a period of time according to the expiration time. Every time users visit the site through a browser, they will send cookie along with the HTTP request, which is part of the http protocol and has nothing to do with language and framework. The server determines whether the user can treat him as a logged-in user by judging the cookie sent. But the cookie is sent by client browsers or even other programs, which means that the cookie sent may have been tampered with in a fake. So the server has to use some kind of authentication mechanism to determine whether it is the cookie sent by itself. The verification mechanism is to include a hash value in the cookie and the raw data that generates the string of hash values. After receiving the cookie, the server takes out the original data, and then generates a hash value according to the original method to compare with the sent hash value. If it is the same, it trusts the cookie, otherwise it must be an illegal request. For example, my Yii website generates a cookie like this:
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
Cookie name is an MD5 value uniformly generated by the website. The value of cookie value consists of two parts, which is a string generated by the hashData method. The first part is the hash value, followed by the original value. In other words, the front 1cbb64bdea3e92c4ab5d5cb16a67637158563114 is the hash value, followed by the original value. This hash value is a 40-bit string generated with SHA1. The server compares the following original value with the passed hash value through the algorithm hash to know that it is a legitimate and illegal request. What about the CAPTCHA?
If the server simply uses the following original value directly with SHA1 or MD5,hash, the person sending the request can modify the original value and hash value at will to pass the verification of the server. Because the SHA1 algorithm is public, everyone can use it. So the server needs to add a verification code that the client does not know when hash to generate a hash value that the client cannot get the correct hash through the original value (a little around:). This is why CAPTCHA is needed. And this verification code must be universal for the whole station, so the above getValidationKey method is to generate a unique verification code for the whole station 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 every request.
At the end of the login process, the generated cookie is sent to the browser. It can be used to verify the next request.
The above is all the contents of the article "sample Analysis of the login process of the Yii framework". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.