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 rules
  • auth_item → Stores roles and permissions
  • auth_item_child → Defines parent-child relationships between roles and permissions
  • auth_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