yii2之RBAC权限控制

一、简单自带的ACF静态权限过滤控制

1. 配置:

'components' => [
    'authManager' => [
        'class' => 'yii
bacPhpManager',
    ],
]

2. controllers/AuthController.php

<?php
namespace backendcontrollers;

use Yii;
use backendcontrollersbaseBaseController;

class AuthController extends BaseController
{
    public function actionAccess()
    {
        $auth = Yii::$app->authManager;
        // 创建和添加角色
        $admin = $auth->createRole('admin');
        $auth->add($admin);
        // 将角色分配到用户
        $auth->assign($admin, 1);
    }
}
# 访问auth/access进行创建,需要新建文件夹rbac

3. 注册控制

public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['captcha', 'logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [ // 控制器方法绑定到角色
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['admin']
                    ]
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

 二、动态自定义的权限控制

1. controller/AuthController.php

<?php
namespace backendcontrollers;

use Yii;
use backendcontrollersbaseBaseController;
use backend
bacAuthorDelete;

/**
 * 静态授权和动态授权之需使用其中一个即可
 * 静态授权:通过权限过滤behaviors实现
 * 动态授权:权限的分配和校验通过php代码动态实现
 */
class AuthController extends BaseController
{
    // FAC静态授权管理
    public function actionAccess()
    {
        $auth = Yii::$app->authManager;
        // 创建和添加角色
        $admin = $auth->createRole('admin');
        $auth->add($admin);
        // 将角色分配到用户
        $auth->assign($admin, 1);

        return 'success';
    }

    // 动态授权管理
    public function actionAuth()
    {
        $auth = Yii::$app->authManager;
        // 删除全部授权
        $auth->removeAll();

        // 添加权限
        $siteSignup = $auth->createPermission('site/signup');
        $siteSignup->description = '用户注册';
        $auth->add($siteSignup);
        $userDelete = $auth->createPermission('user/delete');
        $userDelete->description = '用户删除';
        $auth->add($userDelete);
        $postDelete = $auth->createPermission('post/delete');
        $postDelete->description = '文章删除';
        $auth->add($postDelete);
        $recruitDelete = $auth->createPermission('recruit/delete');
        $recruitDelete->description = '招聘删除';
        $auth->add($recruitDelete);
        $feedDelete = $auth->createPermission('contact/delete');
        $feedDelete->description = '留言删除';
        $auth->add($feedDelete);
        // 添加规则
        $authorDeleteRule = new AuthorDelete;
        $auth->add($authorDeleteRule);
        // 添加权限,绑定规则
        $authorDelete = $auth->createPermission('authorDelete');
        $authorDelete->description = '允许作者删除自己的文章';
        $authorDelete->ruleName = $authorDeleteRule->name; // 绑定规则
        $auth->add($authorDelete);
        
        // 添加角色
        $admin = $auth->createRole('admin');
        $auth->add($admin);
        $author = $auth->createRole('author');
        $auth->add($author);

        // 为角色赋予权限
        $auth->addChild($admin, $siteSignup);
        $auth->addChild($admin, $userDelete);
        $auth->addChild($admin, $postDelete);
        $auth->addChild($admin, $recruitDelete);
        $auth->addChild($admin, $feedDelete);

        $auth->addChild($authorDelete, $postDelete); // 将postDelete作为authorDelete子规则
        $auth->addChild($author, $authorDelete);
        
        // 将角色分配到用户
        $auth->assign($admin, 1);

        return 'success';
    }

    public function actionError()
    {
        return $this->render('error');
    }
}

2. rbac/AuthorDelete.php

<?php
namespace backend
bac;

use yii
bacRule;

class AuthorDelete extends Rule
{
    public $name = 'authorDelete';

    public function execute($user, $item, $params)
    {
        return isset($params['createdBy']) ? $params['createdBy'] == $user : false;
    }
}

2. siteController.php

// behaviors
'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error', 'signup'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['captcha', 'logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
// signup
    public function actionSignup()
    {
        $this->layout = 'login';

        if (!Yii::$app->user->can('site/signup')) {
            $this->layout = 'main';
            return $this->redirect('/auth/error');
        }
            
        
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {

                    $auth = Yii::$app->authManager;
                    $author = $auth->createRole('author');
                    $auth->assign($author, Yii::$app->user->id);
                    
                    return $this->goHome();
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }
原文地址:https://www.cnblogs.com/maoriaty/p/9273012.html