定制 birkof/rbac-bundle 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

birkof/rbac-bundle

Composer 安装命令:

composer require birkof/rbac-bundle

包简介

Symfony PhpRabcBundle allow to use RBAC control access for symfony project

README 文档

README

PhpRBACBundle is symfony 7 bundle with full access control library for PHP. It provides NIST Level 2 Standard Hierarchical Role Based Access Control as an easy to use library to PHP developers. It's a rework of the phprbac.net library made by OWASP for symfony 6.

Table of Content

How it works ?

Go to https://phprbac.net/ :) to have the representation of permissions and roles as well as their interactions.

Roles and Permissions

A hierarchical RBAC model of a system Blue: roles, Gray: users, Yellow: permissions

Installation

just include the package with composer:

composer require olivier127/rbac-bundle

register the bundle inside config/bundles.php

return [
    ...
    PhpRbacBundle\PhpRbacBundle::class => ['all' => true],
];

Add the PhpRbacBundle\Entity\UserRoleTrait inside the User entity class to add the rbac role relation.

Update the database schema with doctrine migration or doctrine schema update to create all the tables

Configuration

Prepare Symfony

Specify the different sections requiring prior authentication in the firewall security configuration section.

Access control only applies to authenticated sections of the website. Therefore, we will use basic ROLE_USER for all users. ROLE_ADMIN can be used for the main administrator but his rights will only be allocated by being associated with the role '/' of the roles tree.

example :

# config/packages/security.yaml
security:
    # ...

    role_hierarchy:
        ROLE_ADMIN: ROLE_USER

    access_control:
        - { path: ^/backend, roles: ROLE_USER }
        - { path: ^/todolist, roles: ROLE_USER }

Add PhpRbac configuration

You must create your own entities for driving permissions and roles.

example :

/* src/Entity/Role.php */
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use PhpRbacBundle\Entity\Role as EntityRole;
use PhpRbacBundle\Repository\RoleRepository;

#[ORM\Entity(repositoryClass: RoleRepository::class)]
#[ORM\Table('my_roles')]
class Role extends EntityRole
{

}
/* src/Entity/Permission.php */
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use PhpRbacBundle\Entity\Permission as EntityPermission;
use PhpRbacBundle\Repository\PermissionRepository;

#[ORM\Entity(repositoryClass: PermissionRepository::class)]
#[ORM\Table('my_permissions')]
class Permission extends EntityPermission
{

}

add php_rbac.yaml to associate theses entities to the rbac core

# config/packages/php_rbac.yaml
php_rbac:
  no_authentication_section:
    default: deny
  resolve_target_entities:
    user: App\Entity\User
    role: App\Entity\Role
    permission: App\Entity\Permission

Roles and permissions creation

Add all the roles and the permissions you need with the RoleManager and the PermissionManager

examples :

to add a permission to the root

/** @var PhpRbacBundle\Core\PermissionManager $manager */
$manager = $this->container->get(PermissionManager::class);
$permission = $manager->add("notepad", "Notepad", PermissionManager::ROOT_ID);

To add a chain or permission

/** @var PhpRbacBundle\Core\PermissionManager $manager */
$manager = $this->container->get(PermissionManager::class);
$manager->addPath("/notepad/todolist/read", ['notepad' => 'Notepad', 'todolist' => "Todo list", "read" => "Read Access"]);

Make the rbac relations

Adding roles use same methods

for the example, i use the chain role "/editor/reviewer". The reviewer is the subrole of the editor, the editor is the subrole of the root "/".

/** @var PhpRbacBundle\Core\RoleManager $manager */
$manager = $this->container->get(RoleManager::class);
$manager->addPath("/editor/reviewer", ['editor' => 'Editor', 'reviewer' => "Reviewer"]);

Assign permissions to roles

/** @var PhpRbacBundle\Core\RoleManager $manager */
$manager = $this->container->get(RoleManager::class);
$editorId = $manager->getPathId("/editor");
$editor = $manager->getNode($editorId);
$reviewerId = $manager->getPathId("/editor/reviewer");
$reviewer = $manager->getNode($reviewerId);

$manager->assignPermission($editor, "/notepad");
$manager->assignPermission($reviewer, "/notepad/todolist/read");
$manager->assignPermission($reviewer, "/notepad/todolist/write");

The editor role will have /notepad permission and all sub permissions while the reviewer role will only have /notepad/todolist/read and /notepad/todolist/write permissions

Assign Role to the user and check permission

If the UserRoleTrait is in the class User, you will have addRbacRole. Just add the role in this entity

/** @var PhpRbacBundle\Core\RoleManager $manager */
$manager = $this->container->get(RoleManager::class);
$editorId = $manager->getPathId("/editor");
$editor = $manager->getNode($editorId);

$user = $userRepository->find($userId);
$user->addRbacRole($user);
$userRepository->add($user, true);

To test a user's permission or role, use the PhpRbacBundle\Core\Rbac class.

$rbacCtrl = $this->container->get(Rbac::class);
$rbacCtrl->hasPermission('/notepad', $userId);
$rbacCtrl->hasRole('/editor/reviewer', $userId);

RBAC for controller

Just add attribute is granted like this example. The attributes IsGranted and HasRole check the security with the current user.

namespace App\Controller;

...
use PhpRbacBundle\Attribute\AccessControl as RBAC;

#[Route('/todolist')]
#[RBAC\IsGranted('/notepad/todolist/read')]
class TodolistController extends AbstractController
{
    #[RBAC\IsGranted('/notepad/todolist/read')]
    #[Route('/', name: 'app_todolist_index', methods: ['GET'])]
    public function index(TodolistRepository $todolistRepository): Response
    {
        ...
    }

    #[RBAC\IsGranted('/notepad/todolist/write')]
    #[Route('/new', name: 'app_todolist_new', methods: ['GET', 'POST'])]
    public function new(Request $request, TodolistRepository $todolistRepository): Response
    {
        ...
    }

    #[RBAC\IsGranted('/notepad/todolist/read')]
    #[Route('/{id}', name: 'app_todolist_show', methods: ['GET'])]
    public function show(Todolist $todolist): Response
    {
        ...
    }

    #[RBAC\IsGranted('/notepad/todolist/write')]
    #[Route('/{id}/edit', name: 'app_todolist_edit', methods: ['GET', 'POST'])]
    public function edit(Request $request, Todolist $todolist, TodolistRepository $todolistRepository): Response
    {
        ...
    }

    #[RBAC\IsGranted('/notepad/todolist')]
    #[Route('/{id}', name: 'app_todolist_delete', methods: ['POST'])]
    public function delete(Request $request, Todolist $todolist, TodolistRepository $todolistRepository): Response
    {
        ...
    }
}

the first RBAC\IsGranted on the class check the lowest permission to access to the controller with the current user. The RBAC\IsGranted on each action check the minimum permission to make action work.

In the example :

  • The permission /notepad/todolist/read gives the access to the all controller and so index and show action.
  • The permission /notepad/todolist/write gives the access to edit the todolist
  • The permission /notepad/todolist parent to the read and write permission gives the access to delete

The permission /notepad/todolist has also the read and write permission.

Voter based Rbac

With RbacVoter, you can use symfony security to check the user rbac permissions (not the roles).

example:

    #[IsGranted('/todolist/index', statusCode: 403, message: 'Access denied for user')]
    #[Route('/', name: 'app_todo_list_index', methods: ['GET'])]
    public function index(TodoListRepository $todoListRepository): Response

You need to set the security access control to be unanimous (all the voter must be ok)

add this lines to config/packages/security.yaml

security:
    ...
    access_decision_manager:
        strategy: unanimous
        allow_if_all_abstain: false

Symfony CLI commands

The install command sets the root node role and permission and associates them.

  security:rbac:install

Add permission into the rbac permissions tree

security:rbac:permission:add

Add permission into the rbac roles tree

security:rbac:role:add

Assign a permission to a role

security:rbac:role:assign-permission

Assign a role to a user

security:rbac:user:assign-role

Theses commandes are interactives.

Twig

test if user has a role

{% if hasRole('/the/role') %}
...
{% endif %}

test if user has a permission

{% if hasPermission('/the/permission') %}
...
{% endif %}

birkof/rbac-bundle 适用场景与选型建议

birkof/rbac-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 118 次下载、GitHub Stars 达 0, 最近一次更新时间为 2023 年 09 月 25 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「symfony」 「security」 「bundle」 「rbac」 「role」 「owasp」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 birkof/rbac-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 birkof/rbac-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 birkof/rbac-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 118
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 25
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 12
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-09-25