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:
In this tutorial, we will implement RBAC in Yii2 using the built-in yii\rbac\DbManager.
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 the following command to create necessary tables:
php yii migrate --migrationPath=@yii/rbac/migrationsThis 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 usersrbac/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/initYou 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);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');
}
}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; ?>Rules allow dynamic access control based on user attributes.
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;
}
}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
}If you want an interface for managing RBAC roles, you can use Yii2-admin extension:
composer require mdmsoft/yii2-adminModify 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/migrationsNow, you can access the UI at:
http://yourdomain.com/adminYou now have a complete RBAC system in Yii2 that:
Sign in to join the discussion and post comments.
Sign in