Yii框架登录流程分析_php实例
本文详细分析了Yii框架的登录流程。分享给大家供大家参考。具体分析如下:
Yii对于新手来说上手有点难度,特别是关于session,cookie和用户验证。现在我们就Yii中登录流程,来讲讲Yii开发中如何设置session,cookie和用户验证方面的一些通用知识
1. 概述
Yii是一个全栈式的MVC框架,所谓全栈式指的是Yii框架本身实现了web开发中所要用到的所有功能,比如MVC,ORM(DAO/ActiveRecord), 全球化(I18N/L10N), 缓存(caching), 基于jQuery Ajax支持(jQuery-based AJAX support), 基于角色的用户验证(authentication and role-based access control), 程序骨架生成器(scaffolding), 输入验证(input validation), 窗体小部件(widgets), 事件(events), 主题(theming), web服务(Web services),日志(logging)等功能. 详见官方说明.
这里要说的只是Yii的登录流程. 用Yii开发一般是用一个叫做Yii shell的控制台工具生成一个程序的骨架,这个骨架为我们分配好了按MVC方式开发web程序的基本结构,并且是一个可以直接运行的程序. 如果你了解 Ruby on Rails的话,原理是一样的.
2.网站登录流程
生成的程序中有一个protected目录,下面的controllers目录有个叫SiteController.php的文件,这个文件是自动生成的,里面有一个叫actionLogin的文件.程序登录流程默认就是从来开始的. Yii把类似于 http://domain.com/index.php?r=site/login 这样的地址通过叫router的组件转到上面说的actionLogin方法里的. 这个路由的功能不是的这里说的重点.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));
}
首先初始化一个LoginForm类,然后判断是否是用户点了登录后的请求(查看请求中有没有POST数据),如果是的话则先验证输入($model->validate)然后尝试登录($model->logiin),如果都成功,就跳转到登录前的页面,否则显示登录页面.
3.框架登录流程
LoginForm类继承于CFormModel,间接继承于CModel,所以他提供了CModel提供了一些像验证和错误处理方面的功能.其中的login方法就是执行验证操作的.方法首先通过用户提供的用户名和密码生成一个用来表示用户实体的UserIdentity类,该类中的authenticate方法执行实际的验证动作,比如从数据库中判断用户名和密码是否匹配. LoginForm类的login方法通过查询authenticate是否有错误发生来判断登录是否成功.如果成功则执行Yii::app()->user->login方法来使用户真正的的登录到系统中. 前面讲到的这些流程是用户程序提供的,而Yii::app()->user->login也就是CWebUser的login方法是Yii框架提供的流程.我们来看看他做了些什么.下面是该方面的代码,位于(Yii)webauthCWebUser.php文件中.
$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))));
}
}
参数$identity是上面登录时生成的UserIdentity类,里面包含了基本的用户信息,如上面的Id,Name,还有可能是其它自定义的数据getPersistentStates. 程序首先把$identity中的数据复制到CWebUser的实例中,这个过程包括了生成相应的session,其实主要目的是生成session.然后根据参数$duration(cookie保存的时间)和allowAutoLogin属性来判断是否生成可以用来下次自动登录的cookie.如果是则生成cookie(saveToCookie).
$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);
}
首先是新建一个CHttpCookie,cookie的key通过getStateKeyPrefix方法取得,该方法默认返回md5('Yii.'.get_class($this).'.'.Yii::app()->getId());即类名和CApplication的Id,这个Id又是crc32函数生成的一个值.这个具体的值是多少无关紧要. 但是每次都是产生一样的值的. 接着设置expire,cookie的过期时间,再新建一个array,包含了基本数据,接着比较重要的是计算取得cookie的值,$app->getSecurityManager()->hashData(serialize($data)), getSecurityManager返回一个CSecurityManager的对象,并调用hashData方法.
$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调用computHMAC方法生成一个hash值. hash的算法有SHA1和MD5两种,默认是用SHA1的. hash的时候还要生成一个validationKey(验证码)的,然后把验证码和要hash的值进行一些故意安排的运算,最终生成一个40位的SHA1,hash值. hashData方法最终返回的是computeHMAC生成的hash值和经序列化的原始数据生成的字符串.这个过程有也许会有疑问. 如为什么要有验证码?
我们先来看一下基于cookie的验证是怎么操作的.服务器生成一个cookie后发送的浏览器中,并根据过期时间保存在浏览器中一段时间.用户每次通过浏览器访问这个网站的时候都会随HTTP请求把cookie发送过去,这是http协议的一部分, 与语言和框架无关的. 服务器通过判断发过来的cookie来决定该用户是否可以把他当作已登录的用户.但是cookie是客户端浏览器甚至其它程序发过来的,也就是说发过来的cookie可能是假的中被篡改过的.所以服务器要通过某种验证机制来判断是否是之后自己发过去的cookie.这个验证机制就是在cookie中包含一个hash值和生成这串hash值的原始数据.服务器接到cookie后取出原始数据,然后按原来的方法生成一个hash值来和发过来的hash值比较,如果相同,则信任该cookie,否则肯定是非法请求.比如我的Yii网站生成了这样一个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是网站统一生成的一个md5值. cookie value的值为两个部分,就是hashData方法生成的一个字符串.前面部分是hash值,后面是原始值.也就是说前面的1cbb64bdea3e92c4ab5d5cb16a67637158563114是hash值,后面是原始值.这个hash值是用SHA1生成的40位的字符串. 服务器把后面的原始值通过算法hash出一个值和这个传过来的hash值比较就知道是合法不审非法请求了. 那验证码呢?
如果服务器只是简单的把后面的原始值直接用SHA1或MD5,hash的话,那发送请求的人可以随意修改这个原始值和hash值来通过服务器的验证.因为SHA1算法是公开的,每个人都可以使用. 所以服务端需要在hash的时候加一个客户端不知道的验证码来生成一个客户端无法通过原始值得到正确hash的hash值(有点绕:) ). 这就是需要验证码的原因.并且这个验证码必须是全站通用的,所以上面的getValidationKey方法是生成一个全站唯一的验证码并保存起来.默认情况下,验证码是一个随机数,并保存在(yii)runtimestate.bin文件中.这样对每个请求来说都是一样的.
登录流程的最后就是把生成的cookie发送到浏览器中. 下次请求的时候可以用来验证.
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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.

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.

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

With the popularity of mobile Internet, Toutiao has become one of the most popular news information platforms in my country. Many users hope to have multiple accounts on the Toutiao platform to meet different needs. So, how to open multiple Toutiao accounts? This article will introduce in detail the method and application process of opening multiple Toutiao accounts. 1. How to open multiple Toutiao accounts? The method of opening multiple Toutiao accounts is as follows: On the Toutiao platform, users can register accounts through different mobile phone numbers. Each mobile phone number can only register one Toutiao account, which means that users can use multiple mobile phone numbers to register multiple accounts. 2. Email registration: Use different email addresses to register a Toutiao account. Similar to mobile phone number registration, each email address can also register a Toutiao account. 3. Log in with third-party account

Xiaohongshu has now been integrated into the daily lives of many people, and its rich content and convenient operation methods make users enjoy it. Sometimes, we may forget the account password. It is really annoying to only remember the account but not be able to log in. 1. How to log in if Xiaohongshu only remembers the account? When we forget our password, we can log in to Xiaohongshu through the verification code on our mobile phone. The specific operations are as follows: 1. Open the Xiaohongshu App or the web version of Xiaohongshu; 2. Click the "Login" button and select "Account and Password Login"; 3. Click the "Forgot your password?" button; 4. Enter your account number. Click "Next"; 5. The system will send a verification code to your mobile phone, enter the verification code and click "OK"; 6. Set a new password and confirm. You can also use a third-party account (such as

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.
