Home php教程 PHP开发 Yii2 framework study notes (6) -- RBAC

Yii2 framework study notes (6) -- RBAC

Dec 30, 2016 am 10:00 AM

In addition to skins, there is also a very important function point in the background preparation work, which is permission control.

Yii2 provides a basic framework for permission control, using RBAC (Role Based Access Control), role-based access control.

To put it simply, different roles have different permissions. For example, the role has admin/guest. Admin can browse pages and manage users, while guest users can only browse pages, etc. A specific user can be bound to a role to exercise the permissions of that role.

Copy the vendor/yiisoft/yii2/rbac/migration/m140506_102106_rbac_init.php file to the console/migration file.

In the yii directory, run yii migrate. You will be prompted whether to run the script we just copied in. Enter yes. After completion, you can see that four new tables have been created in the database.

Yii2 framework study notes (6) -- RBAC

For the specific functions of these tables, please refer to http://blog.csdn.net/yiifans/article/details/27528327
I won’t go into details here, mainly explaining how to Use rbac.

First we make some configurations in our code.

common/config/main-local.php, change authManager to call the database, as follows

...     
 'components' => [  
        ...  
        'authManager' => [  
            'class' => 'yii\rbac\DbManager',  
            'defaultRoles' => ['guest'],  
        ],  
        ...  
 ],  
...
Copy after login

Write a command line script to initialize rbac and use rbac.

Create a new RbacController.php under console/controllers/

First of all, the controller under console/controllers is run through the command line tool yii in the yii root directory, and also supports route , that is, the actionInit method of RbacController is called using yii rbac/init.

The code of RbacController is as follows

<?php

namespace console\controllers;

use yii\console\Controller;
class RbacController extends Controller {
	/**
	 * Init base roles
	 */
	public function actionInit() {
		
		$auth = \Yii::$app->authManager;
		
		$auth->removeAll();
		
		$managerUser = $auth->createPermission("managerUser");
		$managerUser->description = "manage user list";
		$auth->add($managerUser);
		
		$guest = $auth->createRole("guest");
		$auth->add($guest);
		
		$admin = $auth->createRole("admin");
		$auth->add($admin);
		$auth->addChild($admin, $managerUser);
	}
	
	/**
	 * Assign a specific role to the given user id 
	 * @param int $userid
	 * @param string $role
	 */
	public function actionAssign($userid, $role) {
		$auth = \Yii::$app->authManager;
		$roleItem = $auth->getRole($role);
		If ($roleItem == null) {
			throw new Exception("the role is not found");
		}
		$auth->assign($roleItem, $userid);
	}
}
Copy after login

The php-doc will be displayed in the command line tool, enter yii help, the result is as follows

Yii2 framework study notes (6) -- RBAC

First enter yii rbac/init, then two roles will be created, admin and guest. Admin will have managerUser permissions, but guest will not.

Then enter yii rbac/assign 1 admin, which is to assign an admin role to the user with userid 1.

After the preparation is completed, test whether the permissions take effect.

Create new backend/controllers/UserController.php, override the behaviors method, and configure different permissions for different actions. Here we add configuration to the manager-user action that requires manageUser permissions to access. The specific code is as follows.

<?php
namespace backend\controllers;

use yii\web\Controller;
use yii\filters\AccessControl;
class UserController extends Controller {
	
	public function behaviors() {
		return [ 
			&#39;access&#39; => [ 
				&#39;class&#39; => AccessControl::className (),
				&#39;rules&#39; => [ 
					[ 
						&#39;actions&#39; => [ &#39;update-userprofile&#39;],
						&#39;allow&#39; => true,
						&#39;roles&#39; => [ &#39;@&#39; ]
					],
					[
						&#39;actions&#39; => [ &#39;manage-user&#39;],
						&#39;allow&#39; => true,
						&#39;roles&#39; => [ &#39;admin&#39; ]
					]
				] 
			],
		];
	}
	
	public function actionUpdateUserprofile()
	{
		return "sth";
	}
	
	public function actionManageUser() {
		return "inside";
	}
}
Copy after login

The role is @, which means that any logged-in user can access, and the role is admin, which means that only users with the role of admin can access.

You can test the results.

When admin user accesses

Yii2 framework study notes (6) -- RBAC

When non-admin user accesses

Yii2 framework study notes (6) -- RBAC

The above is Yii2 framework learning Notes (6) -- RBAC content, please pay attention to the PHP Chinese website (www.php.cn) for more related content!


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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
How to remove jquery in yii2 How to remove jquery in yii2 Feb 17, 2023 am 09:55 AM

How to remove jquery from yii2: 1. Edit the AppAsset.php file and comment out the "yii\web\YiiAsset" value in the variable $depends; 2. Edit the main.php file and add the configuration "'yii" under the field "components" \web\JqueryAsset' => ['js' => [],'sourcePath' => null,]," to remove the jquery script.

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,

A few selected CTF exercises will help you learn the yii2 framework! A few selected CTF exercises will help you learn the yii2 framework! Feb 23, 2022 am 10:33 AM

This article will introduce you to the yii2 framework, share a few CTF exercises, and use them to learn the yii2 framework. I hope it will be helpful to everyone.

How to install Redis extension using YII2 framework How to install Redis extension using YII2 framework May 26, 2023 pm 06:41 PM

1. You need to download the windows version of the master branch of yii2-redis with composer 2. Unzip and copy it to vendor/yiisoft 3. Add 'yiisoft/yii2-redis'=>array('name'=>'yiisoft to extensions.php under yiisoft /yii2-redis','version'=>'2.0.

How to display error prompts in yii2 How to display error prompts in yii2 Apr 18, 2025 pm 11:09 PM

In Yii2, there are two main ways to display error prompts. One is to use Yii::$app-&amp;gt;errorHandler-&amp;gt;exception() to automatically catch and display errors when an exception occurs. The other is to use $this-&amp;gt;addError(), which displays an error when model validation fails and can be accessed in the view through $model-&amp;gt;getErrors(). In the view, you can use if ($errors = $model-&amp;gt;getErrors())

How to manage RBAC permissions in ThinkPHP6? How to manage RBAC permissions in ThinkPHP6? Jun 12, 2023 am 08:10 AM

With the continuous development of the Internet and the widespread use of applications, more and more websites and applications require access control to ensure the security of sensitive information and resources. With the continuous development of the project and the continuous increase of functions, the RBAC permission management system has become a very popular and mature solution. In this article, we will introduce how to use RBAC for permission management in the ThinkPHP6 framework. What is RBAC permission management? RBAC (Role-BasedAccess

Master the role in PHP-Based Access Control (RBAC) authentication Master the role in PHP-Based Access Control (RBAC) authentication Aug 07, 2023 pm 03:39 PM

Mastering the Role in PHP - BasedAccessControl (RBAC) Authentication Introduction: Authentication is an essential feature when developing web applications. Role-BasedAccessControl (RBAC) is a commonly used authentication mode that manages access control around roles, making the distribution of permissions more flexible and easier to maintain. This article will introduce how to implement RBAC authentication in PHP and provide relevant code examples. 1. Overview of the role of RBAC

Latest best practices for Java JAAS Latest best practices for Java JAAS Feb 23, 2024 pm 10:52 PM

1. JAAS Overview JavaJAAS (JavaAuthenticationandAuthorizationService) is a framework for multi-system single sign-on (SSO) integration, role-based access control (RBAC) and authorization management. JAAS allows applications to protect access to data or resources and define access control mechanisms. 2. The latest best practices of JAAS 1. Use JAAS for authentication JAAS provides two main authentication methods: Token-based authentication: This method uses tokens (for example, username and password) to verify user identity. Certification-based authentication: This method uses certification (for example, a digital certificate) to verify the user's identity. 2

See all articles