Yii authorization role-based access control (RBAC)
1: Basic concepts
A role is a collection of permissions (for example: create posts, modify posts). A role can be assigned to one or more users. To check whether a user has a specific permission, the system checks whether the role containing the permission is assigned to the user.
You can use a rule rule to associate with a role or permission. A rule is represented by a piece of code, and the execution of the rule is performed when checking whether a user meets this role or permission. For example, the "modify post" permission could use a rule that checks whether the user is the creator of the post. During the permission check, if the user is not the post creator, then he (she) will be considered not to have the permission to "modify posts".
Both roles and permissions can be organized hierarchically. In certain cases, a role may consist of other roles or permissions, which in turn may consist of other permissions. Yii implements a so-called local order hierarchy, which contains more specific tree levels. A role can contain a permission, but not vice versa. (Translator's Note: It can be understood that roles are at the top and permissions are at the bottom. If permissions are encountered from top to bottom, roles cannot appear further down)
2: Configure RBAC
At the beginning Before defining authorization data and performing access checks, you need to configure the application component yiibaseApplication::authManager. Yii provides two sets of authorization managers: yiirbacPhpManager and yiirbacDbManager. The former uses PHP scripts to store authorization data, while the latter uses a database to store authorization data. If your application does not require a large number of dynamic roles and permissions management, you may consider using the former
1: Use yiirbacPhpManager
return [ // ... 'components' => [ 'authManager' => [ 'class' => 'yii\rbac\PhpManager', ], // ... ], ];
After the configuration is completed, you can use Yii::$app-> ;authManager to access authManager
yiirbacPhpManager saves RBAC data in files in the @app/rbac directory by default. If the permission level data will be modified at runtime, make sure that the WEB server process has write permissions for the directory and the files in it.
2: Use yiirbacDbManager
(1) Configure yiirbacDbManager
return [ // ... 'components' => [ 'authManager' => [ 'class' => 'yii\rbac\DbManager', // uncomment if you want to cache RBAC items hierarchy // 'cache' => 'cache', ], // ... ], ];
Note here:
If you are using Yii’s basic template, the above For configuration, you need to configure it in both the config/console.php and config/web.php files. If you are an advanced template of Yii, you only need to configure it once in the common/config/main.php file
(2) Generate the required permission table
If you use yiirbacDbManager, you need to generate 4 database tables to store permission data (they all have default table names. If you need to modify the table name, configure yiirbacDbManager Modify when required)
itemTable: This table stores authorization entries (Translator's Note: roles and permissions). The default table name is "auth_item" .
itemChildTable: This table stores the hierarchical relationship of authorization entries. The default table name is "auth_item_child".
assignmentTable: This table stores the assignment of authorization entries to users. The default table name is "auth_assignment".
ruleTable: This table stores rules. The default table name is "auth_rule".
Execute in the project directory
yii migrate --migrationPath=@yii/rbac/migrations
After executing the above command, at this time we The four tables mentioned above will be generated in the database
If you do not use the detailed command to generate the database, you can change the contents of vendoriisoftyii2rbacmigrationsschema-mysql.sql Copy it to the database and run it to generate the data table
After generating the corresponding permission table, we can use Yii::$app->authManager to access authManager
3: Establish authorization data
1: Add (create) permissions (generate permission data in the auth_item table, type is 2 indicating permissions)
$auth = Yii::$app->authManager;// 添加 "createPost" 权限$createPost = $auth->createPermission('createPost'); $createPost->description = '创建了createPost权限'; $auth->add($createPost);
2: Create a role (generate role data in the auth_item table, type is 1 means role)
$auth = Yii::$app->authManager; $role = $auth->createRole('author'); $role->description = '创建了author角色'; $auth->add($role);
3: Grant permissions to the role
(1)Give the role the specified permissions
$auth = Yii::$app->authManager; $createPost = $auth->createPermission('createPost');//创建权限对象 $role = $auth->createRole('author');//创建角色对象 $auth->addChild($role, $createPost); //添加对应关系(给author角色添加createPost权限)
(2)Give the role all the permissions of the specified role
$auth = Yii::$app->authManager; $role1 = $auth->createRole('author1');//创建角色对象 $role2 = $auth->createRole('author2');//创建权限对象 $auth->addChild($role1, $role2); //添加对应关系(给author1角色添加author2角色所有权限)
4: Assign roles to users
$auth = Yii::$app->authManager; $role = $auth->createRole('author');//创建角色对象$auth->assign($role, 1); #1是IdentityInterface::getId()返回的id,及用户表的id
Four: Verify permissions
\Yii::$app->user->can($action) #$action表示权限\Yii::$app->user->can('createPost') #判断用户是否具有createPost权限
Get the user’s role
$auth = Yii::$app->authManager; $roles = $auth->getRolesByUser($userId);
Get the user’s permissions
$auth = Yii::$app->authManager; $roles = $auth->getPermissionsByUser($userId);
The above is a simple understanding of role-based access control (RBAC). For details, please refer to Yii’s official documentation
The above is the detailed content of Yii authorization role-based access control (RBAC). For more information, please follow other related articles on the PHP Chinese website!

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 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 you're asking "What is Yii?" check out my previous tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and outlines what's new in Yii 2.0, released in October 2014. Hmm> In this Programming with Yii2 series, I will guide readers in using the Yii2PHP framework. In today's tutorial, I will share with you how to leverage Yii's console functionality to run cron jobs. In the past, I've used wget - a web-accessible URL - in a cron job to run my background tasks. This raises security concerns and has some performance issues. While I discussed some ways to mitigate the risk in our Security for Startup series, I had hoped to transition to console-driven commands

In modern software development, building a powerful content management system (CMS) is not an easy task. Not only do developers need to have extensive skills and experience, but they also need to use the most advanced technologies and tools to optimize their functionality and performance. This article introduces how to use Yii2 and GrapeJS, two popular open source software, to implement back-end CMS and front-end visual editing. Yii2 is a popular PHPWeb framework that provides rich tools and components to quickly build

Yii framework: This article introduces Yii's method of converting objects into arrays or directly outputting them into json format. It has certain reference value and I hope it can help you.
