Basic RBAC implementation

Hello everyone!

I’m making this little how-to for everyone new to the Yii2 Framework who is having a hard time implementing RBAC on their apps, maybe because of lack of experience or with the tutorials found on the web hard to follow or lacking of examples.

(This is how I solved the rbac implementation on my small basic app, but may vary on what you need)

Ok, this is what I’ve done:

  1. Install and configure the user and rbac modules, both from Dektrium (the instructions are in their respective github pages). You must follow all steps: install, configure and update your database schema with the migration files included.

You can include the login to the navbar by putting this as part of your navbar:

if (Yii::$app->user->isGuest) {

        array_push($navItems, [

            'label' => 'Sign In', 'url' => ['/user/security/login']



  1. Follow the instructions on these 2 videos from the DoingITEasy channel:



I suggest you watching both and practicing the given examples. Create your roles and assign them to your users (the rbac module brings an UI for doing this, but is more clear once you know how it works at a DB level)

  1. Implement the restrictions to you controllers actions by adding this to every action:

    public function actionIndex()


        if(Yii::$app->user->can('user')) // 'user' is my role (or auth_item as shown in the video


            $searchModel = new RegionSearch();

            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

            return $this->render('index', [

                'searchModel' => $searchModel,

                'dataProvider' => $dataProvider,


        } else


            throw new ForbiddenHttpException;



In my case the RBAC needs where plain simple: Guests users can’t access anything, Registered users (or just ‘users’) can only access the index and view page of every model, and finally ‘editor’ can do all CRUD operations on every model.

Of course this has the con that you must add the above code to every action you need to control the access, but as I wrote at the beginning, my app is very little and has only a few Controllers.

Hope this will be helpful for all the people having trouble implementing RBAC in their apps.