yii 权限分级式访问控制的实现(非RBAC法)——已验证
验证和授权——官方文档:
http://www.yiichina.com/guide/topics.auth
http://www.yiiframework.com/doc/guide/1.1/zh_cn/topics.auth
相关类参考手册:
http://www.yiichina.com/api/CWebUser
http://www.yiichina.com/api/CAccessRule
http://www.yiichina.com/api/CUserIdentity
可参考文章:
http://my.oschina.net/u/873762/blog/98697
http://www.yiiframework.com/wiki/60/
yii 权限分级式访问控制的实现(非RBAC法)
主要参考资料来源:yii官网http://www.yiiframework.com/wiki/60/ 我只是做了小小的完善。
yii framework 提供了2套权限访问系统,一套是简单的filter(过滤器)模式,另一套是复杂全面的RBAC模式,我这里要讲的是第一套(因为我也刚刚学到这里)。如 果你有研究过YII官方的demo blog,一定知道,比如,由gii自动生成的user模块,自动附带了简单的filter权限分配功能,具体细节请参照blog手册的“用户验证”一章 节,以及yii官方指南的“验证和授权”一章节。(注意,我这里所指的模块,只是我个人对与user有关的文件的统称,与yii文件系统的模块 (module)含义不同。)
关于权限分配的文件大多在controllers里,比如打开UserController.php文件你会看到2个类函数。
public function filters()
{
return array(
'accessControl', // 实现CRUD操作的访问控制。
'postOnly + delete',
);
} public function accessRules() //这里就是访问规则的设置。
{
return array(
array('allow', // 允许所有用户执行index,view动作。
'actions'=>array('index','view'),
'users'=>array('*'), <span></span>
),
array('allow', // 只允许经过验证的用户执行create, update动作。
'actions'=>array('create','update'),
'users'=>array('@'), // @号指所有注册的用户
),
array('allow', // 只允许用户名是admin的用户执行admin,delete动作
'actions'=>array('admin','delete'),
'users'=>array('admin'),
), //admin就是指用户名是admin的用户,以硬编码的形式分配用户权限。
array('deny', // 拒绝所有的访问。
'users'=>array('*'),
),
);
}
关于更多的访问规则的设定请参照官方文件http://www.yiiframework.com/doc/api/1.1/CAccessControlFilter
好了,现在要开始按照我们自己的需求设置适合自己的权限分配了。我们希望filter访问控制模式能更完美一点,按照常识,我们希望它能按照数据库里user表里不同级别用户,实行不同的授权,而不是用硬编码的形式控制。
回到demo blog,我先对数据库的tbl_user表做修改,在原来的基础上加上role一项。对原来的用户信息记录添加role的value为"管理员"或"一般用户"("admin"或"user")。
然后依次执行以下3个步骤:
1. 创建组件WebUser,它是对CWebUser的扩展。
2. 修改config/main.php文件。
3.修改accessRules()。
具体细节如下:
1.WebUser.php 组件代码:
在protected\components\ 下新建WebUser.php
<?php
/**
* UserIdentity represents the data needed to identity a user.
* It contains the authentication method that checks if the provided
* data can identity the user.
*
* this file must be stored in:
* protected/components/WebUser.php
*/
class WebUser extends CWebUser
{ // Store model to not repeat query.
private $_model; /**
* @return first name.
* @access it by Yii::app()->user->first_name
*/
public function getFirst_Name()
{
$user = $this->loadUser(Yii::app()->user->id);
return $user->first_name;
} /**
* This is a function that checks the field 'role'
* in the User model to be equal to 1, that means it's admin
* @return boolean
* @access it by Yii::app()->user->isAdmin()
*/
public function isAdmin()
{
$user = $this->loadUser(Yii::app()->user->id);
if ($user == null) {
return 0;
} else {
return $user->role == "admin";
} } /**
* Load user model.
* Returns the data model based on the primary key given in the GET variable.
* @param integer $id the ID of the model to be loaded
* @return User the loaded model
*/
protected function loadUser($id = null)
{
if ($this->_model === null) {
if ($id !== null) {
$this->_model = User::model()->findByPk($id);
}
}
return $this->_model;
} /**
* This method is called after the user is successfully logged in.
* You may override this method to do some postprocessing (e.g. log the user
* login IP and time; load the user permission information).
* @param boolean $fromCookie whether the login is based on cookie.
*/
public function afterLogin($fromCookie)
{
//Yii::app()->request->redirect('/index.php/user/create'); if(!Yii::app()->user->isGuest){
$uid = Yii::app()->user->id;
$uip = Yii::app()->request->userHostAddress; //获取用户IP
User::model()->updateAll(array('logintime'=>time(), 'loginip'=>$uip), 'id=:id', array(':id'=>$uid));
} parent::afterLogin($fromCookie);
} /**
* This method is invoked right after a user is logged out.
* You may override this method to do some extra cleanup work for the user.
*/
/*
public function afterLogout()
{
//Yii::app()->request->redirect('/index.php/user/index'); parent::afterLogout();
}
*/
}
2.在config/main.php找到如下代码,添加标红色的代码。
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
'class'=>'WebUser',
),
)
3.找到需要更改权限的controller类,对accessRules()函数做修改,比如对前文的accessRules()函数做如下修改:
public function accessRules() //这里就是访问规则的设置。
{
return array(
array('allow', // 允许所有用户执行index,view动作。
'actions'=>array('index','view'),
'users'=>array('*'), //*号标识所有用户包括注册的、没注册的、一般的、管理员级的
),
array('allow', // 只允许经过验证的用户执行create, update动作。
'actions'=>array('create','update'),
'users'=>array('@'), // @号指所有注册的用户
),
array('allow',
'actions'=>array('admin','delete'),
/**
* expression: 设定一个PHP表达式。它的值用来表明这条规则是否适用。
* 在表达式,你可以使用一个叫$user的变量,它代表的是Yii::app()->user。
* 这个选项是在1.0.3版本里引入的。
* 'expression' => '$user->isAdmin()', //即这样也可以
* 'expression' => '$user->isAdmin() || $user->isAuthor()', //也可以加多条判断
*/
'expression' => 'yii::app()->user->isAdmin()',
//这样只有标识为“管理员”的用户才能访问admin,delete动作
),
array('deny', // 拒绝所有的访问。
'users'=>array('*'),
),
);
}
工作完成!
From: http://my.oschina.net/u/873762/blog/98697
附:
官网blog Demo 验证修改:
在protected\components\ 下新建UserIdentity.php
<?php
/**
* UserIdentity represents the data needed to identity a user.
* It contains the authentication method that checks if the provided
* data can identity the user.
*/
class UserIdentity extends CUserIdentity
{
private $_id; public function authenticate()
{
//$record = User::model()->findByAttributes(array('id' => Yii::app()->user->id));
$record = User::model()->findByAttributes(array('username' => $this->username));
if ($record === null) {
$this->errorCode = self::ERROR_USERNAME_INVALID;
}
/*elseif ($record->password !== md5($this->password)) {
$this->errorCode = self::ERROR_PASSWORD_INVALID;
}*/
elseif ($record->password !== $this->password) {
$this->errorCode = self::ERROR_PASSWORD_INVALID;
}
else {
$this->_id = $record->id;
//$this->setState('roles', $record->role); //未生效
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
} public function getId()
{
return $this->_id;
}
} ?>
在用户登陆时则调用如下代码:
$identity = new UserIdentity($username,$password);
if($identity->authenticate()) {
Yii::app()->user->login($identity);
} else {
echo $identity->errorMessage;
}
在用户退出时调用了Yii::app()->user->logout();
yii 权限分级式访问控制的实现(非RBAC法)——已验证的更多相关文章
- Yii 权限分级式访问控制实现(非RBAC法)
以下由我们在信易网络公司开发项目的时候终结出的一些经验 主要参考资料:yii官网http://www.yiiframework.com/wiki/60/yii framework 提供了2套权限访问系 ...
- YIi 权限管理和基于角色的访问控制
验证和授权(Authentication and Authorization) 定义身份类 (Defining Identity Class) 登录和注销(Login and Logout) 访问控制 ...
- Nagios ’status.cgi‘文件权限许可和访问控制漏洞
漏洞名称: Nagios ’status.cgi‘文件权限许可和访问控制漏洞 CNNVD编号: CNNVD-201307-013 发布时间: 2014-02-21 更新时间: 2014-02-21 危 ...
- OpenSSH ‘mm_newkeys_from_blob’函数权限许可和访问控制漏洞
漏洞名称: OpenSSH ‘mm_newkeys_from_blob’函数权限许可和访问控制漏洞 CNNVD编号: CNNVD-201311-117 发布时间: 2013-11-12 更新时间: 2 ...
- Spring Security实现基于RBAC的权限表达式动态访问控制
昨天有个粉丝加了我,问我如何实现类似shiro的资源权限表达式的访问控制.我以前有一个小框架用的就是shiro,权限控制就用了资源权限表达式,所以这个东西对我不陌生,但是在Spring Securit ...
- 算法笔记_013:汉诺塔问题(Java递归法和非递归法)
目录 1 问题描述 2 解决方案 2.1 递归法 2.2 非递归法 1 问题描述 Simulate the movement of the Towers of Hanoi Puzzle; Bonus ...
- 权限系统设计(0):权限系统设计基本概念改需-MAC/RBAC引子
此篇主要对权限系统设计所涉的一些专业术语重点梳理.从我们windows的文件系统 自主访问控制 到基于角色访问控制. 权限设计基本术语 对后面会用到的词汇做一个简要说明 什么是权限(许可) 权限(Pr ...
- sshpass-Linux命令之非交互SSH密码验证
sshpass-Linux命令之非交互SSH密码验证 参考网址:https://www.cnblogs.com/chenlaichao/p/7727554.html ssh登陆不能在命令行中指定密码. ...
- 【转】sshpass-Linux命令之非交互SSH密码验证
sshpass-Linux命令之非交互SSH密码验证 ssh登陆不能在命令行中指定密码.sshpass的出现,解决了这一问题.sshpass用于非交互SSH的密码验证,一般用在sh脚本中,无须再次 ...
随机推荐
- 更新ACCESS数据库出现“字段太小而不能接受所要添加的数据的数量。试着插入或粘贴较少的数据。”的解决方法
今天进行数据调试时出现“字段太小而不能接受所要添加的数据的数量.试着插入或粘贴较少的数据.”,跟踪发现是在更新数据库的数据时出现的. 打开数据库表格发现出错的数据字段类型被定义为“文本”,也就是数据最 ...
- css3动画使用技巧之——transform-delay为负值时的应用。
<html> <head> <title>css3动画delay为负值时的效果</title> <meta ch ...
- c#集合解析
什么是集合(collection)? 提供了一种结构化组织任意对象的方式,从.NET 的角度看,所谓的集合可以定义为一种对象,这种对象实现一个或者多个System.Collections.IColle ...
- 分页加查询的sql语句
"SELECT TOP(@pagesize) * FROM T_News WHERE(NewsTitle LIKE @newskey OR NewsContent LIKE @newskey ...
- m个苹果放在n个筐里,每个筐至少一个,所有的筐都一样,有多少种放法
package com.study; import java.io.BufferedReader; import java.io.IOException; import java.io.InputSt ...
- Java多线程初学者指南(8):从线程返回数据的两种方法
从线程中返回数据和向线程传递数据类似.也可以通过类成员以及回调函数来返回数据.但类成员在返回数据和传递数据时有一些区别,下面让我们来看看它们区别在哪. 一.通过类变量和方法返回数据 使用这种方法返回数 ...
- 关于django Models的个人理解和related_name的使用
作为一个新人(刚刚大学还没有毕业就出来实习,可以说是真的什么都不知到,什么都要重新学,但是这样真的可以锻炼自己的意志力和能力).现在在公 司是前端和后端一起坐,所以要学的东西是真的多的让人想不到.在学 ...
- hdu 3018
欧拉回路的题: 主要利用的是并查集,为了节省时间,压缩了它的路径: 代码: #include<cstdio> #include<cstring> #define maxn 10 ...
- OpenIOC
http://wenku.it168.com/d_926300.shtml OpenIOC http://safe.it168.com/a2015/1208/1790/000001790446.sht ...
- Android sqlite 数据库在java代码中的增删改查
private void queryPerson(PersonSQLiteOpenHelper personSQLiteOpenHelper) { SQLiteDatabase sqLiteDatab ...