我需要在YII应用程序的所有页面上强制执行身份验证。为此,我使用http://www.heirbaut.nl/2010/02/23/forcing-a-yii-application-to-authenticate/中的以下代码扩展了SiteController
类:
/**
* @return array action filters
*/
public function filters(){
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules(){
return array(
array('allow', // allow all users to perform 'login'
'actions'=>array('login'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform any action
'users'=>array('@'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
这只会执行它应该执行的操作,将所有未经通知的用户请求重定向到index.php
网址的登录表单。但是index.php?r=person
因此,应用程序的主菜单绕过了这个限制,并且无论是否真实都会出现。
答案 0 :(得分:0)
每个控制器都需要引用该代码。一个选项是创建自己的控制器,扩展CController
并将其放在protected/components
文件夹中
class MyController extends CController{
/**
* @return array action filters
*/
public function filters(){
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules(){
return array(
array('allow', // allow authenticated user to perform any action
'users'=>array('@'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
}
然后在您的控制器类中,您需要扩展MyController
并覆盖accessRules()
以添加任何其他规则
public class SiteController extends MyController{
...
public function accessRules(){
$rules=parent::accessRules();
array_unshift($rules,array(
'allow', // allow all users to perform 'login'
'actions'=>array('login'),
'users'=>array('*'),
));
return $rules;
}
...
}