yii2-authorization

http://www.yiiframework.com/doc-2.0/guide-security-authorization.html

Authorization 是一个验证一个用户是否有足够的权限去做某件事。Yii 提供了两种鉴权方法:

  • Access Control Filter (ACL),用于简单的鉴权。
  • Role-Based Access Control (RBAC),可用于复杂的鉴权。

ACL

RBAC

namespace app\rbac;

use yii\rbac\Rule;
use app\models\Post;

/**
 * Check if authorID mathes user passed via params
 */
class AuthorRule extends Rule
{
    public $name = 'isAuthor';
    
    public function execute($user, $item, $param)
    {
        return isset($params['post']) ? $params['post']->createdBy == $user : false;
    }
}

使用

'rules' => [
    [
        'allow' => true,
        'actions' => ['update'],
        'roles' => ['updatePost'],
        'roleParams' => function($rule) {
            return ['post' => Post::findOne(Yii::$app->request->get('id'))];
        },
    ],
],

配置 RBAC

Using DbManager

return [
    // ...
    'components' => [
        'authManager' => [
            'class' => 'yii\rbac\DbManager',
            // uncomment if you want to cache RBAC items hierarchy
            // 'cache' => 'cache',
        ],
        // ...
    ],
];

然后执行命令:

.yii migrate --migrationPath=@yii/rbac/migrations

Building Authorization Data

Building authorization data is all about the following tasks:

  • defining roles and permissions;
  • establishing relations among roles and permissions;
  • defining rules;
  • associating rules with roles and permissions;
  • assigning roles to users.
./yii migrate/create init_rbac

文件内容如下:

<?php
use yii\db\Migration;

class m170124_084304_init_rbac extends Migration
{
    public function up()
    {
        $auth = Yii::$app->authManager;

        // add "createPost" permission
        $createPost = $auth->createPermission('createPost');
        $createPost->description = 'Create a post';
        $auth->add($createPost);

        // add "updatePost" permission
        $updatePost = $auth->createPermission('updatePost');
        $updatePost->description = 'Update post';
        $auth->add($updatePost);

        // add "author" role and give this role the "createPost" permission
        $author = $auth->createRole('author');
        $auth->add($author);
        $auth->addChild($author, $createPost);

        // add "admin" role and give this role the "updatePost" permission
        // as well as the permissions of the "author" role
        $admin = $auth->createRole('admin');
        $auth->add($admin);
        $auth->addChild($admin, $updatePost);
        $auth->addChild($admin, $author);

        // Assign roles to users. 1 and 2 are IDs returned by IdentityInterface::getId()
        // usually implemented in your User model.
        $auth->assign($author, 2);
        $auth->assign($admin, 1);
    }
    
    public function down()
    {
        $auth = Yii::$app->authManager;

        $auth->removeAll();
    }
}