- Yii2 Framework
-
Introduction & Setup
- Introduction to Yii2 Framework
- Installing Yii2 (Basic & Advanced Templates)
- Understanding Yii2 Directory Structure
- Yii2 Configuration Basics
- Routing & Pretty URLs in Yii2
-
Yii2 Core Concepts
- Yii2 Application Bootstrapping & Lifecycle
- Understanding Yii2 Request & Response Handling
- Working with Yii2 Components & Helpers
- Yii2 Widgets & Using Built-in Widgets
- Yii2 Helpers & Utility Classes
-
Models & Database Operations
- Yii2 Models, Active Record & Database Connections
- CRUD Operations in Yii2
- Yii2 Query Builder & DAO (Direct SQL Queries)
- Handling Relationships in Yii2 Active Record
- Yii2 Migrations & Seeding
-
Views, Layouts & Themes
- Yii2 Views & Layouts
- Yii2 Asset Bundles & Asset Management
- Integrating Bootstrap in Yii2
- Yii2 Theme Integration
- Yii2 Custom Widgets & Reusable Components
-
Forms, Validation & Data Presentation
- Yii2 Forms & Validation
- Using Yii2 GridView & ListView Widgets
- Yii2 Pagination & Sorting
- Yii2 File Uploads
-
Security & User Management
- User Authentication in Yii2
- Role-Based Access Control (RBAC) in Yii2
- Yii2 Security Features
-
Console Commands & Advanced Features
- Yii2 Console Commands
- Yii2 Events & Behaviors
- Yii2 RESTful API Development
- Consuming Third-Party APIs in Yii2
- Yii2 Background Jobs & Queue System
-
Performance Optimization & Caching
- Yii2 Caching Techniques
- Yii2 Performance Optimization
- Debugging & Logging in Yii2
-
Deployment & Best Practices
- Deploying Yii2 Applications
- Yii2 Best Practices & Large-Scale Application Structure
- Yii2 Multilingual & Localization Support
- Yii2 Module Development
- Integrating Yii2 with Frontend Frameworks (Angular/Vue/React)
Role-Based Access Control (RBAC) in Yii2
1. Introduction
RBAC (Role-Based Access Control) is a powerful authorization mechanism that assigns roles and permissions to users. Yii2 provides a flexible RBAC system that allows you to:
- Define roles and permissions
- Assign permissions to roles
- Assign roles to users
- Control access to controllers and actions
- Manage RBAC via database storage
In this tutorial, we will implement RBAC in Yii2 using the built-in yii\rbac\DbManager
.
2. Setting Up RBAC in Yii2
Enable RBAC Component
Modify config/web.php
to enable DbManager:
'components' => [
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
],
Yii2 supports two types of RBAC managers:
PhpManager
→ Stores RBAC rules in PHP files.DbManager
→ Stores rules in a database (Recommended for production).
Run Migrations for RBAC Tables
Run the following command to create necessary tables:
php yii migrate --migrationPath=@yii/rbac/migrations
This will create the following tables in your database:
auth_rule
→ Stores RBAC rulesauth_item
→ Stores roles and permissionsauth_item_child
→ Defines parent-child relationships between roles and permissionsauth_assignment
→ Assigns roles to users
3. Defining Roles and Permissions
Creating an RBAC Seeder (rbac/init
)
Create a console command in commands/RbacController.php
:
namespace app\commands;
use Yii;
use yii\console\Controller;
use yii\rbac\DbManager;
class RbacController extends Controller
{
public function actionInit()
{
$auth = Yii::$app->authManager;
// Clear existing roles and permissions
$auth->removeAll();
// Create Permissions
$createPost = $auth->createPermission('createPost');
$createPost->description = 'Create a post';
$auth->add($createPost);
$updatePost = $auth->createPermission('updatePost');
$updatePost->description = 'Update a post';
$auth->add($updatePost);
// Create Roles
$author = $auth->createRole('author');
$auth->add($author);
$auth->addChild($author, $createPost);
$admin = $auth->createRole('admin');
$auth->add($admin);
$auth->addChild($admin, $updatePost);
$auth->addChild($admin, $author); // Admin inherits author permissions
// Assign roles to users (Assuming user ID 1 is admin, user ID 2 is author)
$auth->assign($admin, 1);
$auth->assign($author, 2);
echo "RBAC roles and permissions have been successfully assigned.\n";
}
}
Run this command to initialize RBAC:
php yii rbac/init
4. Assigning Roles to Users
You can assign roles programmatically using authManager
:
$auth = Yii::$app->authManager;
$role = $auth->getRole('author');
$auth->assign($role, $userId);
To revoke a role:
$auth->revoke($role, $userId);
To check assigned roles:
$roles = Yii::$app->authManager->getRolesByUser($userId);
5. Implementing Access Control in Yii2
Using RBAC in Controllers
Modify your PostController.php
to enforce role-based access:
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
class PostController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'actions' => ['create'],
'allow' => true,
'roles' => ['author'],
],
[
'actions' => ['update'],
'allow' => true,
'roles' => ['admin'],
],
],
],
];
}
public function actionCreate()
{
if (!Yii::$app->user->can('createPost')) {
throw new \yii\web\ForbiddenHttpException('You do not have permission to create posts.');
}
return $this->render('create');
}
public function actionUpdate()
{
if (!Yii::$app->user->can('updatePost')) {
throw new \yii\web\ForbiddenHttpException('You do not have permission to update posts.');
}
return $this->render('update');
}
}
6. Using RBAC in Views
You can also check permissions in views:
<?php if (Yii::$app->user->can('createPost')): ?>
<a href="<?= Yii::$app->urlManager->createUrl(['post/create']) ?>" class="btn btn-primary">Create Post</a>
<?php endif; ?>
7. Implementing Rule-Based Access Control
Rules allow dynamic access control based on user attributes.
Create a Custom Rule
Create AuthorRule.php
inside rbac
folder:
namespace app\rbac;
use yii\rbac\Rule;
class AuthorRule extends Rule
{
public $name = 'isAuthor';
public function execute($user, $item, $params)
{
return isset($params['post']) ? $params['post']->author_id == $user : false;
}
}
Register Rule in RBAC
Modify RbacController.php
:
$rule = new \app\rbac\AuthorRule();
$auth->add($rule);
$updateOwnPost = $auth->createPermission('updateOwnPost');
$updateOwnPost->description = 'Update own post';
$updateOwnPost->ruleName = $rule->name;
$auth->add($updateOwnPost);
$auth->addChild($updateOwnPost, $updatePost);
$auth->addChild($author, $updateOwnPost);
To check this permission:
if (Yii::$app->user->can('updateOwnPost', ['post' => $post])) {
// User can update their own post
}
8. Managing RBAC via UI
If you want an interface for managing RBAC roles, you can use Yii2-admin extension:
composer require mdmsoft/yii2-admin
Modify config/web.php
:
'modules' => [
'admin' => [
'class' => 'mdm\admin\Module',
],
],
'components' => [
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
],
'as access' => [
'class' => 'mdm\admin\components\AccessControl',
'allowActions' => ['site/login', 'site/logout'],
],
Run migrations:
php yii migrate --migrationPath=@mdm/admin/migrations
Now, you can access the UI at:
http://yourdomain.com/admin
9. Conclusion
You now have a complete RBAC system in Yii2 that:
- Manages roles and permissions
- Assigns permissions dynamically
- Restricts access based on user roles
- Supports UI-based management
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- The Ultimate Guide to Artificial Intelligence (AI) for Beginners
- Ideas for Content of Every niche on Reader’s Demand during COVID-19
- Quantum AI – The Future of AI Powered by Quantum Computing
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- Career Guide: Natural Language Processing (NLP)
- Google’s Core Update in May 2020: What You Need to Know
- SQL Joins Explained: A Complete Guide with Examples
- Grow your business with Facebook Marketing
- Why to learn Digital Marketing?
- Exploratory Data Analysis On Iris Dataset
- Loan Default Prediction Project Using Machine Learning
- Store Data Into CSV File Using Python Tkinter GUI Library
- Mastering SQL in 2025: A Complete Roadmap for Beginners
- Top 10 Knowledge for Machine Learning & Data Science Students
- 15 Amazing Keyword Research Tools You Should Explore
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset