如何在一处检查权限?
我不想单独检查每个函数。
我的 RBAC Controller 。
我想检查登录用户对 Controller 中所有操作的权限。现在我必须为 Controller 中的每个操作单独使用 Yii::$app->user->can('...')
$admin = $auth->createRole('Admin');
$moderator = $auth->createRole('Moderator');
$createPost=$auth->createPermission('createPost');
$updatePost=$auth->createPermission('updatePost');
$deletePost=$auth->createPermission('deletePost');
$createCategory=$auth->createPermission('createCategory');
$updateCategory=$auth->createPermission('updateCategory');
$deleteCategory=$auth->createPermission('deleteCategory');
$auth->add($admin);
$auth->add($moderator);
$auth->add($createPost);
$auth->add($updatePost);
$auth->add($deletePost);
$auth->add($createCategory);
$auth->add($updateCategory);
$auth->add($deleteCategory);
这里我为角色分配权限,但我从不使用这些权限,因为在行为中手动写入->(就像您的示例)
目标是什么,在 RBAC 中创建权限,如果这不起作用?如果我想添加高级用户。我只能在 Controller 中添加操作,例如actionPremium 并为高级用户设置行为操作。
例如
行动=>['溢价'] 角色=>['premiumUser']
还有一个问题。 如何在行为中自定义消息错误?
$auth->addChild($admin,$moderator);
$auth->addChild($admin,$createCategory);
$auth->addChild($admin,$updateCategory);
$auth->addChild($admin,$deleteCategory);
$auth->addChild($moderator, $createPost);
$auth->addChild($moderator, $updatePost);
$auth->addChild($moderator, $deletePost);
$auth->assign($admin,1);
$auth->assign($moderator,2);
最佳答案
您可以为行为中的所有操作分配 Controller 允许的权限
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['index','view'], // these action are accessible
//only the yourRole1 and yourRole2
'allow' => true,
'roles' => ['yourRole1', 'yourRole2'],
],
[ // all the action are accessible to superadmin, admin and manager
'allow' => true,
'roles' => ['superAdmin', 'admin', 'manager'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
您在行为中分配的角色用于操作..允许或拒绝..如果角色在行为中具有允许的操作,那么他可以执行,否则他会获得权限被拒绝403..(未授权)..
您还可以使用
检查过程代码中的角色if ( Yii::$app->User->can('admin') ){
.....
yourdCode
....
}
关于php - Yii2 RBAC 检查权限,无需 Controller 中的每个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35417353/