Doubts about Yii2 RBAC

后端 未结 5 2032
情歌与酒
情歌与酒 2021-02-20 07:50

I\'ve been developing web apps using Yii 1.1.14 so far, but now it\'s time for an upgrade.

The company where I work has developed its own Access Control system, and I wa

5条回答
  •  执笔经年
    2021-02-20 08:19

    Yii2 needs a little setup when it comes to using RBAC under your controllers AccessControl. I got around it by making my own AccessRule file.

    namespace app\components;
    
    use Yii;
    
    class AccessRule extends \yii\filters\AccessRule
    {
        protected function matchRole($user)
        {
            if (empty($this->roles)) {
                return true;
            }
            foreach ($this->roles as $role) {
                if(Yii::$app->authManager->checkAccess($user->identity->code, $role))
                    return true;
            }
            return false;
    }
    

    then in your controller u can use something like this:

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'ruleConfig' => [
                    'class' => 'app\components\AccessRule'
                ],
                'rules' => [
                    [
                        'actions' => ['index', 'resource-type'],
                        'allow'=> true,
                        'roles' => ['admin'],
                    ],
                ],
            ],
        ];
    }
    

    Where admin is defined as a auth_item and the user is in the auth_item_assignments.

提交回复
热议问题