Table of Contents
Yii framework login process analysis, yii framework process
Home Backend Development PHP Tutorial Yii framework login process analysis, yii framework process_PHP tutorial

Yii framework login process analysis, yii framework process_PHP tutorial

Jul 13, 2016 am 10:12 AM
yii yii framework Log in

Yii framework login process analysis, yii framework process

This article analyzes the login process of Yii framework in detail. Share it with everyone for your reference. The specific analysis is as follows:

Yii is a bit difficult for novices to get started, especially about sessions, cookies and user authentication. Now let’s talk about the login process in Yii and talk about some general knowledge on how to set up session, cookie and user authentication in Yii development

1. Overview

Yii is a full-stack MVC framework. The so-called full-stack refers to the fact that the Yii framework itself implements all functions used in web development, such as MVC, ORM (DAO/ActiveRecord), globalization (I18N/ L10N), caching, jQuery-based AJAX support, role-based user verification (authentication and role-based access control), program skeleton generator (scaffolding), input validation (input validation), Form widgets (widgets), events (events), themes (theming), web services (Web services), logging (logging) and other functions. See the official description for details.

What I want to talk about here is just the login process of Yii. To develop with Yii, you usually use a console tool called Yii shell to generate the skeleton of a program. This skeleton assigns us the basic structure of developing web programs according to the MVC method. And it is a program that can be run directly. If you know Ruby on Rails, the principle is the same.

2. Website login process

There is a protected directory in the generated program. There is a file called SiteController.php in the controllers directory below. This file is automatically generated and contains a file called actionLogin. The program login process starts from the beginning by default. Yii Transfer an address similar to 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 focus here. actionLogin The code of the method is like this.

Copy code 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 it is a request after the user clicks login (check whether there is POST data in the request). If so, first verify the input ($model->validate) and then try to log in ($ model->logiin), if all are successful, jump to the page before login, otherwise the login page will be displayed.

3. Framework login process

The LoginForm class inherits from CFormModel and indirectly inherits from CModel, so it provides CModel to provide some functions such as verification and error handling. The login method is to perform verification operations. The method first passes the user name and password provided by the user Generate a UserIdentity class to represent the user entity. The authenticate method in this class performs actual verification 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 is successful by querying whether there is an error in authenticate. Success. If successful, execute the Yii::app()->user->login method to allow the user to 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 a process provided by the Yii framework. Let's take a look at what it does. The following is the code in this regard, located in the (Yii)webauthCWebUser.php file.

Copy code 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 parameter $identity is the UserIdentity class generated when logging in above, which contains basic user information, such as the above Id, Name, and possibly other customized data getPersistentStates. The program first copies the data in $identity In the example of CWebUser, this process includes generating the corresponding session. In fact, the main purpose is to generate the session. Then based on the parameters $duration (the time the cookie is saved) and the allowAutoLogin attribute, it is judged whether to generate a cookie that can be used to automatically log in next time. If so, generate a cookie (saveToCookie).

Copy code 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 new CHttpCookie. The key of the cookie is obtained through the getStateKeyPrefix method. This method returns md5('Yii.'.get_class($this).'.'.Yii::app()->getId() by default ); that is, the class name and the Id of CApplication, and this Id is a value generated by the crc32 function. It does not matter what the specific value is. But it will generate the same value every time. Then set expire, the expiration time of the cookie, and then Create a new array that contains basic data. Then the more important thing is to calculate the value of the cookie, $app->getSecurityManager()->hashData(serialize($data)), getSecurityManager returns a CSecurityManager object, and calls hashData Method.

Copy code 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. There are two hash algorithms: SHA1 and MD5. The default is SHA1. When hashing, a verificationKey (verification code) is also generated, and then the verification code and the hash to be The value undergoes some deliberately arranged operations and finally generates a 40-bit SHA1 hash value. The hashData method ultimately returns the hash value generated by computeHMAC and the string generated by the serialized original data. This process may be questionable. Why do we need a verification code?

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 based on the expiration time. Each time the user accesses this website through the browser Cookies are always sent with the HTTP request. This is part of the http protocol and has nothing to do with language and framework. The server determines whether the user can be regarded as a logged-in user by judging the cookie sent. But the cookie is the client's It is sent by the client browser or even other programs, which means that the cookie sent may be fake and tampered with. Therefore, the server needs to use some verification mechanism to determine whether it is a cookie sent by itself later. This verification mechanism is The cookie contains a hash value and the original data that generated the hash value. 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 hash value. cookie, otherwise it will definitely be an 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

Cookie name is an md5 value uniformly generated by the website. The value of cookie value is two parts, which is a string generated by the hashData method. The first part is the hash value, and the second part is the original value. In other words, the previous 1cbb64bdea3e92c4ab5d5cb16a67637158563114 is The hash value is followed by the original value. This hash value is a 40-bit string generated using SHA1. The server hashes the original value through an algorithm to produce a value and compares it with the passed hash value to know whether it is legal and does not review illegal requests. Okay. What about the verification code?

If the server simply hashes the original value directly with SHA1 or MD5, the person who sent the request can modify the original value and hash value at will to pass the server's verification. Because the SHA1 algorithm is public, everyone Everyone can use it. Therefore, the server needs to add a verification code that the client does not know when hashing to generate a hash value that the client cannot get the correct hash from the original value (a bit convoluted:) ). This is what requires a verification code. Reason. And this verification code must be universal for the entire site, so the above getValidationKey method generates a unique verification code for the entire site and saves it. By default, the verification code is a random number and is saved in (yii) runtimestate. bin file. This will be the same for every request.

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

I hope this article will be helpful to everyone’s PHP program design based on the Yii framework.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/920980.htmlTechArticleYii framework login process analysis, yii framework process This article analyzes the Yii framework login process in detail. Share it with everyone for your reference. The specific analysis is as follows: Yii is a bit difficult for novices to get started with...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? Mar 21, 2024 pm 09:41 PM

With the rapid development of social media, Xiaohongshu has become a popular platform for many young people to share their lives and explore new products. During use, sometimes users may encounter difficulties logging into previous accounts. This article will discuss in detail how to solve the problem of logging into the old account on Xiaohongshu, and how to deal with the possibility of losing the original account after changing the binding. 1. How to log in to Xiaohongshu’s previous account? 1. Retrieve password and log in. If you do not log in to Xiaohongshu for a long time, your account may be recycled by the system. In order to restore access rights, you can try to log in to your account again by retrieving your password. The operation steps are as follows: (1) Open the Xiaohongshu App or official website and click the "Login" button. (2) Select "Retrieve Password". (3) Enter the mobile phone number you used when registering your account

What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? Mar 19, 2024 pm 02:00 PM

When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

'Onmyoji' Ibaraki Doji's collection skin can be obtained as soon as you log in, and the new Zen Heart Cloud Mirror skin will be launched soon! 'Onmyoji' Ibaraki Doji's collection skin can be obtained as soon as you log in, and the new Zen Heart Cloud Mirror skin will be launched soon! Jan 05, 2024 am 10:42 AM

Thousands of ghosts screamed in the mountains and fields, and the sound of the exchange of weapons disappeared. The ghost generals who rushed over the mountains, with fighting spirit raging in their hearts, used the fire as their trumpet to lead hundreds of ghosts to charge into the battle. [Blazing Flame Bairen·Ibaraki Doji Collection Skin is now online] The ghost horns are blazing with flames, the gilt eyes are bursting with unruly fighting spirit, and the white jade armor pieces decorate the shirt, showing the unruly and wild momentum of the great demon. On the snow-white fluttering sleeves, red flames clung to and intertwined, and gold patterns were imprinted on them, igniting a crimson and magical color. The will-o'-the-wisps formed by the condensed demon power roared, and the fierce flames shook the mountains. Demons and ghosts who have returned from purgatory, let's punish the intruders together. [Exclusive dynamic avatar frame·Blazing Flame Bailian] [Exclusive illustration·Firework General Soul] [Biography Appreciation] [How to obtain] Ibaraki Doji’s collection skin·Blazing Flame Bailian will be available in the skin store after maintenance on December 28.

Discuz background login problem solution revealed Discuz background login problem solution revealed Mar 03, 2024 am 08:57 AM

The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

How to log in to Kuaishou PC version - How to log in to Kuaishou PC version How to log in to Kuaishou PC version - How to log in to Kuaishou PC version Mar 04, 2024 pm 03:30 PM

Recently, some friends have asked me how to log in to the Kuaishou computer version. Here is the login method for the Kuaishou computer version. Friends who need it can come and learn more. Step 1: First, search Kuaishou official website on Baidu on your computer’s browser. Step 2: Select the first item in the search results list. Step 3: After entering the main page of Kuaishou official website, click on the video option. Step 4: Click on the user avatar in the upper right corner. Step 5: Click the QR code to log in in the pop-up login menu. Step 6: Then open Kuaishou on your phone and click on the icon in the upper left corner. Step 7: Click on the QR code logo. Step 8: After clicking the scan icon in the upper right corner of the My QR code interface, scan the QR code on your computer. Step 9: Finally log in to the computer version of Kuaishou

How to install GitHub Copilot on Windows 11/10 How to install GitHub Copilot on Windows 11/10 Oct 21, 2023 pm 11:13 PM

GitHubCopilot is the next level for coders, with an AI-based model that successfully predicts and autocompletes your code. However, you might be wondering how to get this AI genius on your device so that your coding becomes even easier! However, using GitHub isn't exactly easy, and the initial setup process is a tricky one. Therefore, we created this step-by-step tutorial on how to install and implement GitHub Copilot in VSCode on Windows 11, 10. How to install GitHubCopilot on Windows There are several steps to this process. So, follow the steps below now. Step 1 – You must have the latest version of Visual Studio installed on your computer

How to log in to two devices on Quark How to log in to two devices on Quark Feb 23, 2024 pm 10:55 PM

How to log in to two devices with Quark? Quark Browser supports logging into two devices at the same time, but most friends don’t know how to log in to two devices with Quark Browser. Next, the editor brings users Quark to log in to two devices. Method graphic tutorials, interested users come and take a look! Quark Browser usage tutorial Quark how to log in to two devices 1. First open the Quark Browser APP and click [Quark Network Disk] on the main page; 2. Then enter the Quark Network Disk interface and select the [My Backup] service function; 3. Finally, select [Switch Device] to log in to two new devices.

How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance Mar 13, 2024 pm 04:58 PM

Baidu Netdisk can not only store various software resources, but also share them with others. It supports multi-terminal synchronization. If your computer does not have a client downloaded, you can choose to enter the web version. So how to log in to Baidu Netdisk web version? Let’s take a look at the detailed introduction. Baidu Netdisk web version login entrance: https://pan.baidu.com (copy the link to open in the browser) Software introduction 1. Sharing Provides file sharing function, users can organize files and share them with friends in need. 2. Cloud: It does not take up too much memory. Most files are saved in the cloud, effectively saving computer space. 3. Photo album: Supports the cloud photo album function, import photos to the cloud disk, and then organize them for everyone to view.​

See all articles