Home Backend Development PHP Tutorial 深入解析yii权限分级式访问控制的实现(非RBAC法)_php技巧

深入解析yii权限分级式访问控制的实现(非RBAC法)_php技巧

May 17, 2016 am 09:01 AM
yii Access control

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('*'),           
           ),                   
         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为"管理员"或"一般用户"。
然后依次执行以下3个步骤:
1. 创建组件WebUser,它是对CWebUser的扩展。
2. 修改config/main.php文件。
3.修改accessRules()。
具体细节如下:
1.WebUser.php 组件代码:
复制代码 代码如下:


 // 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
   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
   // access it by Yii::app()->user->isAdmin()
   function isAdmin(){
     $user = $this->loadUser(Yii::app()->user->id);
     if ($user==null)
         return 0;
     else
         return $user->role == "管理员";
   }

   // Load user model.
   protected function loadUser($id=null)
     {
         if($this->_model===null)
         {
             if($id!==null)
                 $this->_model=User::model()->findByPk($id);
         }
         return $this->_model;
     }
 }
 ?>


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',                     // 只允许用户名是admin的用户执行admin,delete动作
             'actions'=>array('admin','delete'),
             'expression'=>'yii::app()->user->isAdmin()',
             //这样只有标识为“管理员”的用户才能访问admin,delete动作
         ),
         array('deny',  // 拒绝所有的访问。
             'users'=>array('*'),
         ),
     );

工作完成!
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 to use Vue for permission management and access control How to use Vue for permission management and access control Aug 02, 2023 pm 09:01 PM

How to use Vue for permission management and access control In modern web applications, permission management and access control is a critical feature. As a popular JavaScript framework, Vue provides a simple and flexible way to implement permission management and access control. This article will introduce how to use Vue to implement basic permission management and access control functions, and attach code examples. Defining Roles and Permissions Before you begin, you first need to define the roles and permissions in your application. A role is a specific set of permissions, and

How to use PHP framework Yii to develop a highly available cloud backup system How to use PHP framework Yii to develop a highly available cloud backup system Jun 27, 2023 am 09:04 AM

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

Access Control Editor cannot be opened in Win10 Access Control Editor cannot be opened in Win10 Jan 03, 2024 pm 10:05 PM

The inability to open the access control editor in win10 is an uncommon problem. This problem usually occurs in external hard drives and USB flash drives. In fact, the solution is very simple. Just open it in safe mode and take a look. Let’s take a look at the details below. tutorial. Win10 cannot open the access control editor 1. In the login interface, hold down shift, click the button, click 2.--, click 3. After restarting, press F5 to try to enter and see if you can enter. Articles related to win10 safe mode>>>How to enter win10 safe mode<<<>>>How to repair the system in win10 safe mode<<<

How Nginx implements access control configuration based on request source IP How Nginx implements access control configuration based on request source IP Nov 08, 2023 am 10:09 AM

How Nginx implements access control configuration based on the request source IP requires specific code examples. In network application development, protecting the server from malicious attacks is a very important step. Using Nginx as a reverse proxy server, we can configure IP access control to restrict access to specific IP addresses to improve server security. This article will introduce how to implement access control configuration based on request source IP in Nginx and provide specific code examples. First, we need to edit the Nginx configuration file

Use Go language to solve large-scale access control problems Use Go language to solve large-scale access control problems Jun 15, 2023 pm 02:59 PM

With the development of the Internet, access control issues have increasingly become an important topic. In traditional permission management, role authorization or access control lists are generally used to control resources. However, this method is often unable to adapt to large-scale access control needs because it is difficult to flexibly implement access control for different roles and resources. To solve this problem, using Go language to solve large-scale access control problems has become an effective method. Go language is a language for concurrent programming. It has excellent concurrency performance and fast compilation.

An in-depth exploration of Nginx's traffic analysis and access control methods An in-depth exploration of Nginx's traffic analysis and access control methods Aug 05, 2023 pm 05:46 PM

An in-depth discussion of Nginx's traffic analysis and access control methods. Nginx is a high-performance open source web server. It is powerful and scalable, so it is widely used in the Internet field. In practical applications, we usually need to analyze Nginx traffic and control access. This article will delve into Nginx's traffic analysis and access control methods and provide corresponding code examples. 1. Nginx traffic analysis Nginx provides many built-in variables that can be used to analyze traffic. Among them, commonly used

Implementing Role-Based Access Control (RBAC): Using PHP and RBAC Implementing Role-Based Access Control (RBAC): Using PHP and RBAC Jun 20, 2023 pm 10:39 PM

With the popularity of Internet applications, we hope to protect data within the application to ensure that sensitive data is not misused or stolen. One of the solutions is to use role-based access control (RBAC). Role-based access control (RBAC) is an access control model based on the relationship between users and roles. The core idea of ​​this model is to link the user's role to the access control operation, rather than linking the access control operation directly to the user. This approach improves the flexibility of access control,

Symfony vs Yii2: Which framework is better for developing large-scale web applications? Symfony vs Yii2: Which framework is better for developing large-scale web applications? Jun 19, 2023 am 10:57 AM

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

See all articles