在yii中新增一个用户验证的方法详解_PHP
因为我要将网站后台和前台做在同一个yii的应用中.但是前台也包含有会员的管理中心.而这两个用户验证是完全不同的,所以需要两个不同登陆页面,要将用户信息保存在不同的cookie或session中.所以需要在一个应用中增加一个用户验证
2.yii的用户验证:
在自定义用户验证前,我们首先要弄清楚yii的验证和授权方式.
为了验证一个用户,我们需要定义一个有验证逻辑的验证类.在yii中这个类需要实现IUserIdentity接口,不同的类就可以实现不同的验证方 法.网站登陆一般需要验证的就是用户名和密码,yii提供了CUserIdentity类,这个类一般用于验证用户名和密码的类.继承后我们需要重写其中 的authenticate()方法来实现我们自己的验证方法.具体代码如下:
Php代码
复制代码 代码如下:
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$record=User::model()->findByAttributes(array('username'=>$this->username));
if($record===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($record->password!==md5($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$record->id;
$this->setState('title', $record->title);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
在用户登陆时则调用如下代码:
Php代码
复制代码 代码如下:
// 使用提供的用户名和密码登录用户
$identity=new UserIdentity($username,$password);
if($identity->authenticate())
Yii::app()->user->login($identity);
else
echo $identity->errorMessage;
用户退出时,则调用如下代码:
Php代码
复制代码 代码如下:
// 注销当前用户
Yii::app()->user->logout();
其中的user是yii的一个components.需要在protected/config/main.php中定义
Php代码
复制代码 代码如下:
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
'loginUrl' => array('site/login'),
),
这里我们没有指定user的类名.因为在yii中默认user为CWebUser类的实例.
我 们现在已经实现了用户的登陆验证和退出.但是现在无论是否登陆,用户都能访问所有的action,所以下一步我们要对用户访问进行授权.在yii里是通过 Access Control Filter即访问控制过滤器来实现用户授权的.我们看一下一个简单的带有访问控制的Controller:
Php代码
复制代码 代码如下:
class AdminDefaultController extends CController
{
public function filters()
{
return array('accessControl');
}
public function accessRules()
{
return array(
array(
'allow',
'users' => array('@'),
),
array(
'deny',
'users' => array('*')
),
);
}
}
我们在filters方法中设置具体的filter.我们可以看到在filters方法返回的array里有accessControl参数,在CController类中有一个filterAccessControl方法:
Php代码
复制代码 代码如下:
public function filterAccessControl($filterChain)
{
$filter=new CAccessControlFilter;
$filter->setRules($this->accessRules());
$filter->filter($filterChain);
}
在里面新建了一个CAccessControlFilter实例,并且在setRules时传入了accessRules()方法返回的参数.
$filter->filter($filterChain)则是继续调用其它filter.
而所有具体的授权规则则是定义在accessRules中:
Php代码
复制代码 代码如下:
public function accessRules()
{
return array(
array('deny',
'actions'=>array('create', 'edit'),
'users'=>array('?'),
),
array('allow',
'actions'=>array('delete'),
'roles'=>array('admin'),
),
array('deny',
'actions'=>array('delete'),
'users'=>array('*'),
),
);
}
具体规则参见yii的手册.
3.新增一个验证体系:
首先我们从CWebUser继承一个CAdminUser:
Php代码
复制代码 代码如下:
class CAdminWebUser extends CWebUser
{
public $loginUrl = array('admin/admin/login');
}
我们需要把他放置到components中
如果是全局应用则通过protected/config/main.php的components小节:
Php代码
复制代码 代码如下:
'user'=>array(
// enable cookie-based authentication
'class' => 'CAdminUser',
'allowAutoLogin'=>true,
'loginUrl' => array('site/login'),
),
如果是在modules中则在模块类的init方法中添加如下代码:
Php代码
复制代码 代码如下:
$this->setComponents(array(
'adminUser' => array(
'class' => 'CAdminWebUser',
'allowAutoLogin' => false,
)
));
最后调用方式
Php代码
复制代码 代码如下:
//全局应用
Yii::app()->getComponent('adminUser');
//在模块中
Yii::app()->controller->module->getComponent('adminUser');
但仅仅这样还不够,我们还需要修改Controller的filter,我们需要自定义一个filter,来实现另一个用户的验证和授权
第一步自定义一个filter:
Php代码
复制代码 代码如下:
class CAdminAccessControlFilter extends CAccessControlFilter
{
protected function preFilter($filterChain)
{
$app=Yii::app();
$request=$app->getRequest();
$user = Yii::app()->controller->module->getComponent('adminUser');
$verb=$request->getRequestType();
$ip=$request->getUserHostAddress();
foreach($this->getRules() as $rule)
{
if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
break;
else if($allow {
$this->accessDenied($user);
return false;
}
}
return true;
}
}
再重写CController类的filterAccessController方法
Php代码
复制代码 代码如下:
public function filterAccessControl($filterChain)
{
$filter = new CAdminAccessControlFilter();
$filter->setRules($this->accessRules());
$filter->filter($filterChain);
}
//在这里我们使用自定义的filter类替换了原来的filter
OK,到这里我们就可以在此Controller的accessRules()中指定adminUser的授权了

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



With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

In the win11 system, we need to log in every time we enter the system. However, if there is only one account in our system or there is no need to protect the account, we do not need to log in every time. At this time, we can cancel the login account by canceling the password. , let’s take a look at the specific methods below. How to cancel the login account in win11 1. First, click the arrow button in the center of the taskbar and quickly select the "Start" option. 2. Next, enter the system settings interface and quickly click the "Run" option to start. 3. Next, enter the command: controluserpasswords2 and press the Enter key. 4. Click to open the "User Account Properties" option and uncheck "To use this machine, users must enter

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

If we want to set privacy for our computer, we can set a power-on password for the computer, and it is very convenient. It only needs to be done in the settings. Let’s take a look. How to set a power-on password in win11: 1. First, right-click the "Start" menu and click Settings. 2. Then click "Account". 3. Then click "Login Options". 4. Then find "Password" and click Add. 5. Finally, it can be added successfully.

How to perform user input validation and security filtering in PHP? When developing web applications, user input validation and security filtering are very important aspects. If user input is not handled correctly, it can lead to various security vulnerabilities, such as cross-site scripting (XSS) and SQL injection attacks. Therefore, validating and security filtering user input is one of the important measures to protect web applications. This article will introduce how to perform user input validation and security filtering in PHP. Data type validation Before receiving user input, it first needs to be validated
