Add Role-based access control in Yii 2 Framework

Yii 2 uses an extremely easy-to-use form of user access control called permissions. When employed, each user can be given permission (exact mechanics are not important right now). When necessary, the application can check whether authenticated user has this permission by calling:

Yii::$app->user->can($permission);

Here, the $permission argument is the string that is the textual label for the permission. That’s it.

There are two important additional features provided by the concept of permissions:

  • A permission can be declared as the child of other permission. However, when some user has the parent permission, he is automatically considered granted of all his child permissions.
  • We can assign some additional parameterized constraint named rule to the permission. Technically, a rule is a PHP function that takes parameters as arguments. If this function returns false, even if the user is assigned the permission in question, he is considered blocked anyway.
Recommended :  Everything you should know about Elastic Search

This scheme is certainly lacking a concept of role to be called role-based access control (RBAC). Yii 2 has roles working the same way as the permissions. In fact, they are implemented using the same base class \yii\rbac\Item, differing only by a value of one class constant. There is no Yii::$app->user->is($role) invocation, so you need to check for a user being assigned some role by the same call to \yii\web\User.can(). Roles in RBAC of Yii 2 are meant to be used only as a group of permissions.



Pin It on Pinterest

Shares
Scroll Up

Get the best in web dev

Join dunebook.com and recieve best in web dev , once a week FREE

An email has been Sent to your Inbox ! Please Confirm your Subscription :)