Home Backend Development PHP Tutorial Yii authorization role-based access control (RBAC)

Yii authorization role-based access control (RBAC)

Jun 29, 2019 pm 05:49 PM
yii

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',
        ],        // ...
    ],
];
Copy after login

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',
        ],        // ...
    ],
];
Copy after login

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

Yii authorization role-based access control (RBAC)

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);
Copy after login

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);
Copy after login

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权限)
Copy after login

(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角色所有权限)
Copy after login

4: Assign roles to users

$auth = Yii::$app->authManager;
$role = $auth->createRole('author');//创建角色对象$auth->assign($role, 1); #1是IdentityInterface::getId()返回的id,及用户表的id
Copy after login

Four: Verify permissions

\Yii::$app->user->can($action) #$action表示权限\Yii::$app->user->can('createPost') #判断用户是否具有createPost权限
Copy after login

Get the user’s role

$auth = Yii::$app->authManager;
$roles = $auth->getRolesByUser($userId);
Copy after login

Get the user’s permissions

$auth = Yii::$app->authManager;
$roles = $auth->getPermissionsByUser($userId);
Copy after login

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!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 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

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

Data query in Yii framework: access data efficiently Data query in Yii framework: access data efficiently Jun 21, 2023 am 11:22 AM

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

How to use Yii3 framework in php? How to use Yii3 framework in php? May 31, 2023 pm 10:42 PM

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.

Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Jun 19, 2023 am 08:09 AM

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

Yii2 Programming Guide: How to run Cron service Yii2 Programming Guide: How to run Cron service Sep 01, 2023 pm 11:21 PM

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

PHP development: Use Yii2 and GrapeJS to implement back-end CMS and front-end visual editing PHP development: Use Yii2 and GrapeJS to implement back-end CMS and front-end visual editing Jun 15, 2023 pm 11:48 PM

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

How to convert yii objects into arrays or directly output to json format How to convert yii objects into arrays or directly output to json format Jan 08, 2021 am 10:13 AM

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.

See all articles