php - Yii2 RBAC 检查权限,无需 Controller 中的每个操作

标签 php oop yii2

如何在一处检查权限?
我不想单独检查每个函数。

我的 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/

相关文章:

php - PHP解析/语法错误;以及如何解决它们

c# - 面向对象的概念适用于C语言吗?

oop - Nim 中的无根据方法是什么?

php - 如何禁用 Yii2 中的按钮

widget - 使用 yii2-ckeditor-widget 自定义 ckeditor 以接受 html 和 body 标签

Php,检查对象数组中是否存在属性=值的对象

php - MySQL:多条件查询

php - 检查 WooCommerce 中 Hook 功能破坏网站上的用户角色

javascript - 实例化动态类

php - Yii2: Ajax 调用多个参数