yii's rbac, install arbc module extension from the beginning,To debug and analyze the principle,It also took a lot of time off and on.Of course after you understand it,You will findyii's abrc is more convenient, Allows you to easily implement resource control access,Very powerful.Organize your study notes now,share.Although the authmangner component implements rbac, it does not implement visual editing management. At present, there are two better extension modules, srbac and right.We use them to conveniently manage roles, tasks, and operations.

Role-based access control is a simple and powerful centralized access control.The authmanager component based on the yii framework implements a hierarchical rbac, which can help us solve some problems of resource control access encountered in development.

For these two expansion modules,In fact, the functions are similar.Only the interface is different.See what style you like,Just select that module to test.As for installation and commissioning,You just download them,There are detailed introductions.Below we analyze the principle of authmanager component implementation.

Authorized items,Is to determine whether a user is allowed to operate a specific resource,Determine by checking whether the user belongs to a role that has permission to access the resource.Here we have to understand,Authorized items,The relationship between roles, tasks, operations.

1. Authorized items can be divided into,Roles, tasks, operations;

2.The role can be composed of several tasks;

3.The task can consist of several operations;

4. Operation is a license,Do not divide.

Also mentioned here,Business rules issues,It is actually a piece of PHP code that will be executed when checking permissions.

Below we analyze the implementation of rbac, three tables are needed:the structure of authassignment, authitem, authitemchild:

itemname varchar (64) role name,Case sensitive

userid varchar (64) user id, which is the id of the user table in your project

bizrule text business rules,A piece of php code

data text serialized array,Used to provide parameters to bizrule

name varchar (64) same itemname in authassignment

type integer type identification (0,1,2)


| -------- 0 means operation

| -------- 1 means task

| -------- 2 means role

description text

bizrule text business rules,A piece of php code

data text serialized array,Used to provide parameters to bizrule

parent varchar (64) parent name,[Role name, or task];

children varchar (64) The name of the child object.[Task name, or operation];

Use the authentication method cwebuser ::checkaccess (), which is explained below with a demo code:

if (yii ::app ()->user->checkaccess (what, $params)) {
  //what --- role, or task, or operation,  //params --- is the parameter key-value passed into the business rule;

The following demonstrates the specific operation of a user to delete an article:

$params=array ("uid" =>$id);
if (yii ::app ()->user->checkaccess ("delarticle", $params)) {
  //Check if the current user has permission to delete articles
  //and use business rules,Check that the user id is equal to the author id in the article

yii-srbac- Privilege extension module works

1.Set permissions rule table:can be placed in the module configuration file

public function init () {
  //Operation permission table,The following fields must exist:
  //itemname role name/id,  //type authorization item type/1 (task) or 2 (role),  //bizrule permission/logical operation expression is false to have permission operation,  //data data/yii not used yet
  yii ::app ()->authmanager->itemtable="authitem";
  //Member group-permission correspondence table,The following fields must exist:
  //child child role/id,  //parent parent role/id, this table can be executed in a loop,Multi-level inheritance
  yii ::app ()->authmanager->itemchildtable="uthitemchild";
  //Member-member group correspondence table,Member group can be the operation name directly,The following fields must exist:
  //itemname role name/id,  //userid user name/id,  //bizrule permission/logical operation expression is false to have permission operation,  //data data/yii not used yet
  yii ::app ()->authmanager->assignmenttable="zd_mem_glog";

2, implementation rules,Where the controller inherits the base class sbasecontroller, the original controller

class productcontroller extends sbasecontroller
class sbasecontroller extends controller

3. The sbasecontroller inherits the base class controller and adds beforeaction to implement permission verification.

protected function beforeaction ($action) {
  //Load module delimiter
  $del=helper ::findmodule ("srbac")->delimeter;
  //Get the previous module name
  $mod=$this->module! == null?$this->module-&id;id. $del:"";
  $contrarr=explode ("/", $this->id);
  $contrarr [sizeof ($contrarr)-1]=ucfirst ($contrarr [sizeof ($contrarr)-1]);
  $controller=implode (".", $contrarr);
  $controller=str_replace ("/", ".", $this->id);
  //Generate a static page module + separator + controller (capital letter) + method (capital letter) Example:model-controlleraction
  if (sizeof ($contrarr) == 1) {
   $controller=ucfirst ($controller);
  $access=$mod. $controller. ucfirst ($this->action->id);
  //Verify whether the address of the visited page is in the always allowed list,Is returned with permission
  if (in_array ($access, $this->allowedaccess ())) {
   return true;
  //Verify that srbac is installed,Not installing
Returned permission access
  if (! yii ::app ()->getmodule ("srbac")->isinstalled ()) {
   return true;
  //Verify that srbac is turned on,Not opening,Returned permission access
  if (yii ::app ()->getmodule ("srbac")->debug) {
   return true;
  if (! yii ::app ()->user->checkaccess ($access) || yii ::app ()->user->isguest) {
   $this->onunauthorizedaccess ();
  } else {
   return true;

4, cdbauthmanager read the current user role

public function getauthassignments ($userid)
  $rows=$this->db->createcommand ()
    ->Select ()
    ->From ($this->assignmenttable)
    ->Where ("userid =:userid", array (":userid" =>$userid))
    ->Queryall ();
  $assignments=array ();
  foreach ($rows as $row)
    if (($data [email protected] ($row ["data"])) === false)
    $assignments [$row ["itemname"]]=new cauthassignment ($this, $row ["itemname"], $row ["userid"], $row ["bizrule"], $data);
  return $assignments;

5, cdbauthmanager read role corresponding permissions

public function getauthitem ($name)
  $row=$this->db->createcommand ()
    ->Select ()
    ->From ($this->itemtable)
    ->Where ("name =:name", array (":name" =>$name))
    ->Queryrow ();
  if ($row! == false)
    if (($data [email protected] ($row ["data"])) === false)
    return new cauthitem ($this, $row ["name"], $row ["type"], $row ["description"], $row ["bizrule"], $data);
    return null;

6, cdbauthmanager read permission corresponding operation

protected function checkaccessrecursive ($itemname, $userid, $params, $assignments)
  if (($item=$this->getauthitem ($itemname)) === null)
    return false;
  yii ::trace ("checking permission" ". $item->getname ()." "", "system.web.auth.cdbauthmanager");
  if (! isset ($params ["userid"]))
    $params ["userid"]=$userid;
  if ($this->execuanniterule ($item->getbizrule (), $params, $item-&getdata ()))
    if (in_array ($itemname, $this->defaultroles))
      return true;
    if (isset ($assignments [$itemname]))
      $assignment=$assignments [$itemname];
      if ($this->execuanniterule ($assignment->getbizrule (), $params, $assignment->getdata ()))
        return true;
    $parents=$this->db->createcommand ()
      ->Select ("parent")
      ->From ($this->itemchildtable)
      ->Where ("child =:name", array (":name" =>$itemname))
      ->Querycolumn ();
    foreach ($parents as $parent)
      if ($this->checkaccessrecursive ($parent, $userid, $params, $assignments))
        return true;
  return false;

7, cauthmanager verify permissions

public function executebizrule ($bizrule, $params, $data)
  return $bizrule === "" || $bizrule === null || ($this->showerrors?eval_r ($bizrule)!=0:@eval_r ($bizrule)!=0);

Third, srbac test

Some configuration information in srbac that needs attention

srbac theme environment construction,And how to integrate it into our specific project (you can put it in the modules directory and then do some configuration in the configuration file)

When installing, we can choose whether to generate some test data,Of course, it doesn't matter if it is not generated,We can manually configure some data according to its rules.

Before introducing the configuration of the data,We need to know a bit about how the srbac module works:

The srbac module implements permission control through the mapping relationship between roles-- tasks-- operations.

users corresponds to our users

roles corresponds to all role names required by our system

operations corresponds to the names of all the specific operations we need to perform permission management (such as a specific action, we only allow a certain role to access)

In the main interface of srbac we can see three icons, which correspond to different operations.

Let's first create some data information we need (corresponding to the first icon):

Create a new specific operation:Note the naming of the operation here.Must be in the format controllernameactionname. controller, action name combination,And the first letter of both must be capitalized.

Create a specific task:A task can correspond to multiple operations. We can name tasks according to the corresponding functions. For example:you can use news management to represent news management tasks. The naming here does not have strict format requirements.You just need to be famous.

Create specific roles:This is very simple,Just enter the role we need.

OK, the data creation is complete.Next, we come to the assign page (corresponding to the second icon), and map the specific data.

According to what I said earlier,Assign operations to each task, and then we assign tasks to specific roles.

Finally, assign roles to the user.

At this step,Our permissions configuration is basically over.

At this time, we can click the third icon to view the permission information of our specific user.

After confirmation,We can then verify our permissions.

However, there is one final step before that,We want to confirm that the debug mode of srbac is turned off.

Because looking at the source code, we find thatIf debug mode is on,Our rights management will not work.

You can check it in config/main.php:

"modules" =>array (
  "srbac" =>array (
    "userclass" =>"user",    "userid" =>"id",    "username" =>"username",    "debug" =>false, //confirm this field

At this step,Our permissions module is ready to work. Go check if our configuration is normal,Ha ha

  • Previous JavaScript-DOM operation-Windowdocument object
  • Next Installation and use of VNC remote desktop program in Centos