To setup Role Based Access Control in Yii 2.0, there are three steps:
Step 1: Defining Roles and Permissions (What are the roles: permissions vs. roles)
Role and permission should be defined in common/rbac/items.php
. The file can be either generated by yii rbac/init
command or hand wirtten.
To generate items.php
file, write the definitions in console/controllers/RbacController.php
Refer to http://www.yiiframework.com/doc-2.0/guide-security-authorization.html#generating-rbac-data
Step 2: Defining Rules (Who has what role: roles vs. users)
Rules are to control who can do that. For example we want alow admins (user.group = 1) to be able to manage all posts.
This is done in file common/rbac/UserGroupRule.php
Refer to http://www.yiiframework.com/doc-2.0/guide-security-authorization.html#using-default-roles
Step 3: Checking access in Controller (permissions vs. actions)
Define which permissions/roles to apply to which action. For example permission managePost
only be active for actions create
, view
, update
and delete
.
Refer to http://www.yiiframework.com/doc-2.0/guide-security-authorization.html#using-rules