Role-based access control

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.

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 bacItem, 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 yiiwebUser.can(). Roles in RBAC of Yii 2 are meant to be used only as a group of permissions.

The application component handling the RBAC is called the authorization manager and is accessible as the authManager component by the Yii::$app->authManager property. The previously described yiiwebUser.can() method is a shorthand wrapper around the call to Yii::$app->authManager->checkAccess($user_id, $permission). For convenience, there exists a concept of default role. The list of default role names can be set in the components.authManager.defaultRoles setting in the Application configuration, which corresponds to the yii bacBaseManager::$defaultRoles property. A user is assumed to have the default role all of the time, that is, given the value of defaultRoles as ["guest"], the call to Yii::$app->authManager->checkAccess($user_id, "guest") will always return true.

In the AccessFilter described previously, each rule can be configured to check for the user role. We used the special symbols ? and @ back there, which denoted guests and authenticated users, respectively, but in fact, the role names can be used there.

A big challenge for this system to work is to set up the required associations between users and roles. Let's explore how it's done by making a feature in our example CRM application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.252.204