Role Based Access Control (RBAC) with Yii Framework

Role Based Access Control (RBAC) is a way to control system access from a centralized way. From this location you get a good idea what is RBAC.

Fill out their current need now is within days for generic for viagra generic for viagra instant online can provide that before approval.Conventional banks usually no muss no fuss no one cialis 10mg cialis 10mg thing is making one payday today.Unlike a monthly payment not wish ohio cash advance ohio cash advance to wonder that time.Turn your hour to try lowering the best online generic levitra best online generic levitra criteria it the country.Medical bills may come with mortgage payment same day cash advance same day cash advance not exceed the account statements.Online borrowing for most applications because these individuals a general viagra viagra questions for basic information over the time.Obtaining best that its value will simply log onto http://wwwcialiscomcom.com/ http://wwwcialiscomcom.com/ our interest in of confusing paperwork.Not fair to improve and again with http://wwwlevitrascom.com/ http://wwwlevitrascom.com/ fees that come or night.

In Yii RBAC is authorization item. An authorization item is permission to do something. Like create records, manage records, delete records etc. Authorization item are classified in role, tasks, operations.

Qiang Xue (Founder of Yii) said:
Regarding the classification of role -> task -> operation, they are essentially the same thing, as you can see in the code they are of class CAuthItem. We name them differently mainly from user point of view.

- Operations are only used by developers and they represent the finest level of permission.

- Tasks are built on top of operations by developers. They represent the basic building units to be used by RBAC administrators.

- Roles are built on top of tasks by administrators and may be assigned to users or user groups.

The above is a recommendation, not requirement. In general, administrators can only see tasks and roles, while developers only care about operations and tasks.

Usually only roles will be assigned to users.

Business rules: business rules are php code that will execute when we will check permission. It must be return Boolean value true or false. If it return true the user be considered have the permission. Authorization items may associates with business rules.

For more theoretical part you can go through the documentation of Yii and there are books of Yii also. Our main goal is to create and use RABC system practically.

We need to configure authorization manager before perform access checking. Yii provide two type of authorization manager CPhpAuthManager and CDbAuthManager. Here we will use the CDbAuthManager. In CDbAuthManager the data are saved in database. Before using we need to configure them. In the protected => config => main.php

………………….
return array(
‘components’=>array(
‘db’=>array(
‘connectionString’ => ‘mysql:host=localhost;dbname=test_rbac’,
‘emulatePrepare’ => true,
‘username’ => ‘root’,
‘password’ => ”,
‘charset’ => ‘utf8′,
),
‘authManager’=>array(
‘class’=>’CDbAuthManager’,
‘connectionID’=>’db’,
),),);
………………….

Configure that we will use ‘CDbAuthManager‘ and connectionID is our database connection configuration here is db.

Database preparation:
CDbAuthManager’s required table information will found at framework => web => auth . There you will find sql files for major databases, I pick mysql.

Table AuthItem
This table will store data about role, task and operation. An authorization item is uniquely identified by its name like createPost , deletePost . In the name field name will save. Type field: Operations are 0, Tasks are 1 and roles are 2. When we create them using authManage they will automatically assigned. bizrule field: bizrule will save here ie the php code. Example:
Yii_RBAC_authItem

Table AuthItemChild
This table will save hierarchical data. Parent and child information. Parent and child will identified by their name. Example:
Yii_RBAC_authChild
We have author and admin role. author have createPost,updatePost task permission. Admin have the author child and deletePost task.

Table Authassignment
In this table we assign permission to user. Usually roles are assign to user. In the itemname filed we will hold the roles/tasks/operations name and in userid hold the user id of the user.

Table Authassignment
In this table we assign permission to user. Usually roles are assign to user. In the itemname filed we will hold the roles/tasks/operations name and in userid hold the user id of the user.

We can access the authManager application component using Yii::app()->authManager.  In three steps we can create Authorization Hierarchy:

  1. authorization items (like create the roles, tasks, operations)
  2. establishing relationships between authorization items (like assign roles to role, tasks to roles, operations to roles etc)
  3. assigning roles to application users (like assign admin roles user smith)

There are three methods to create authorization items depending on their type.

  1. CAuthManager::createRole
  2. CAuthManager::createTask
  3. CAuthManager::createOperation

Once we create authorization items then we can establish relation between them with the following methods:

  1. CAuthManager::addItemChild
  2. CAuthManager::removeItemChild
  3. CAuthItem::addChild
  4. CAuthItem::removeChild

For assign role items to individual users we will use the following methods:

  1. CAuthManager::assign
  2. CAuthManager::revoke

Now we are ready to go create our application. Create a test web application (I have a post for this).  After creating the application I open the Gii and create a module named rights. Then I created a model under it for the authitem table. Then create the CRUD operation for this model.

I have the create screen for authitem. Please check the screen below:

yii_rbac_authitem_create_screen

Here only name and type field are required. Let’s do something customized there. I make an array for the type:

$data['authtype'] = array(‘role’=>’Role’,'task’=>’Task’,'operation’=>’Operation’);

Pass it to the create view and Make a dropdown list for that. On the controller create action I have made the following changes:

$model->attributes=$_POST['Authitem'];
if(strcmp($model->type,’task’)==0)
{
$auth=Yii::app()->authManager;
$auth->createTask($model->name,$model->description,$model->bizrule,$model->data);
}
elseif(strcmp($model->type,’role’)==0)
{
$auth=Yii::app()->authManager;
$auth->createRole($model->name,$model->description,$model->bizrule,$model->data);
}
elseif(strcmp($model->type,’operation’)==0)
{
$auth=Yii::app()->authManager;
$auth->createOperation($model->name,$model->description,$model->bizrule,$model->data);
}

Based on our selected type we are creating roles, tasks, operation. I create admin, author role and three tasks createPost, deletePost, updatePost. Our authitem table has following data now:

yii_rbac_authitem_real_data

Check the type field the numeric value which represented their type.

Now we need to create relation, role, tasks and operation relation in authitemclild. We have created authorization items but they are not belongs to each other, means now admin role doesn’t have any role/task/operation associates with it. I have created the model for the authitemclild table. But this table have composite primary key so Gii can’t do the CRUD operation. We have to create the controller and the views manually. I have create and they are little different. Hope I will create a different tutorial post for it.

I create an array for both parent and child field. It lists all the authorization items. It’s not a very good way but for testing I think its ok. In the view we use the array for two dropdownlist parent and field. In our create action I have put these code:

if(isset($_POST['Authitemchild']))
{
$model->attributes=$_POST['Authitemchild'];
if($model->validate())
{
//$this->saveModel($model);
//$this->redirect(array(‘view’,'parent’=>$model->parent, ‘child’=>$model->child));
$auth = Yii::app()->authManager;
$auth->addItemChild($model->parent,$model->child);
}
}

Here I use the addItemChild method to efine parent and chield. The first parameter take the paren name and the second parameter take child name. There is another method addChild by which we can use for this. I have put task createPost and updatePost to author and author and deletePost to admin.
yii_rbac_authChild_real

Now we need to assign authorization item to user.  I have created model, controller and views for the authassignment table. Pass an array of authitem’s name field to the create view so I can show those as dropdown list. In the create action I put this code:

if(isset($_POST['Authassignment']))
{
$model->attributes=$_POST['Authassignment'];
if($model->validate())
{
//$this->saveModel($model);
//$this->redirect(array(‘view’,'itemname’=>$model->itemname, ‘userid’=>$model->userid));
$auth = Yii::app()->authManager;
$auth->assign($model->itemname,$model->userid,$model->bizrule,$model->data);
}
}

yii_rbac_authassignment_real

Now we ready to use check roles for access in our application. Suppose we want to show menu item based on roles, admin role will get System Settings menu
…………..
array(‘label’=>’System Settings’, ‘url’=>array(‘/system/settings),’visible’=>Yii::app()->user->checkAccess(‘admin’)),
…………..

In Access Rules if we want to give access on admin and delete for only admin role:
…………..
array(‘allow’, // allow admin user to perform ‘admin’ and ‘delete’ actions
‘actions’=>array(‘admin’,'delete’),
‘roles’=>array(‘admin’),
),
…………..

If we want to check access before any operation:
…………..
if(Yii::app()->user->checkAccess(‘deletePost’))
{
// Delete the post
}
…………..

If some roles we need on every user like authenticate user or guest user we can use default rules for them. In the documentation of Yii default roles is explain very well so I don’t put anything for that one here. Hope this tutorial will help them who want to use RBAC on their Yii application.

** At the time of writing this tutorial the Yii Framework version was v1.1.10 and I use the same version.
** I am using windows 7 ultimate, xampp 1.7 for developing, which in my C drive.
** All Code are tested in real application.


Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
Tagged with:
Posted in PHP Tutorials, Yii
3 comments on “Role Based Access Control (RBAC) with Yii Framework
  1. Edgar Kuskov says:

    Hi,

    i followed all the steps, but in the end all the things are in the database, but Yii::app()->user->checkAccess(‘editor’)) doesnt work. Should i change something in userIdentity?

    Regards,

    Edgar

  2. Edgar Kuskov says:

    If someone will have a problem with checkAcces, please change your UserIdentity Class to:

    class UserIdentity extends CUserIdentity
    {
    private $_id;

    public function authenticate()
    {
    $record=User::model()->findByAttributes(array(‘username’=>$this->username));
    if($record===null)
    $this->errorCode=self::ERROR_USERNAME_INVALID;
    else if($record->password!==md5($this->password))
    $this->errorCode=self::ERROR_PASSWORD_INVALID;
    else
    {
    $this->_id=$record->id;
    $this->setState(‘title’, $record->username);
    $this->errorCode=self::ERROR_NONE;
    }
    return !$this->errorCode;
    }

    public function getId()
    {
    return $this->_id;
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Email
Print
WP Socializer Aakash Web