如何在yii2中设置全局访问控制?

时间:2018-10-30 23:40:06

标签: yii2 access-control

我有AdminControllerbehavior

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'actions' => ['login'],
                    'allow' => true,
                    'roles' => ['*'],
                ],
                [
                    'actions' => ['index', 'logout'],
                    'allow' => true,
                    'roles' => ['admin', 'editor', 'expert'],
                ],
                [
                    'actions' => ['update', 'delete'],
                    'allow' => true,
                    'roles' => ['admin'],
                ]
            ]
        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'logout' => ['get'],
            ],
        ],
    ]; 
}

然后我为以下项创建子控制器:

  • 默认控制器
  • inf-courses控制器
  • 和其他

如何在父级(AdminController)上使用规则,然后使其起作用? 如果我在deafult中添加类似的规则,则可以,但是在全球范围内无效。

P.S。我做管理面板,然后要: -任何人都可以尝试登录 -访问管理窗格:['admin', 'editor', 'expert'] -注销只能['admin', 'editor', 'expert']

这是具有父级admin的所有模块AdminController的全局规则。

谢谢。

2 个答案:

答案 0 :(得分:0)

如果扩展控制器,然后覆盖behaviors(),则请确保包括以下家长行为:

return ArrayHelper::merge(parent::behaviors(), [
  // your behaviors here
]);

答案 1 :(得分:0)

完成! 我将AdminController设置为:

class AdminController extends Controller {

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['admin', 'editor', 'expert'],
                    ],
                    [
                        'actions' => ['login'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['delete'],
                        'allow' => true,
                        'roles' => ['admin'],
                    ]
                ]
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['get'],
                ],
            ],
        ]; 
    }
}

并为管理员中的每个控制器扩展它