PHPackages                             olivier127/rbac-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. olivier127/rbac-bundle

ActiveSymfony-bundle[Authentication &amp; Authorization](/categories/authentication)

olivier127/rbac-bundle
======================

Symfony PhpRabcBundle allow to use RBAC control access for symfony project

1.1.2(8mo ago)318.3k↓42.9%14[5 issues](https://github.com/Olivier127/rbac-bundle/issues)MITPHPPHP ^8.1

Since Mar 28Pushed 3mo ago2 watchersCompare

[ Source](https://github.com/Olivier127/rbac-bundle)[ Packagist](https://packagist.org/packages/olivier127/rbac-bundle)[ RSS](/packages/olivier127-rbac-bundle/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (7)Versions (19)Used By (0)

PhpRbacBundle
=============

[](#phprbacbundle)

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.

✨ Features
----------

[](#-features)

- ✅ **NIST Level 2 RBAC** - Hierarchical role-based access control
- ✅ **PHP 8.3 + Symfony 7.3** - Modern stack with latest features
- ✅ **Multi-Database** - MySQL, MariaDB, PostgreSQL support
- ✅ **Performance Cache** - 80-90% reduction in database queries
- ✅ **Nested Set Model** - Efficient hierarchical permissions
- ✅ **Attributes Support** - PHP 8 attributes for controllers
- ✅ **Voter Integration** - Symfony Security component integration
- ✅ **Twig Extensions** - Template helpers for permissions
- ✅ **CLI Commands** - Interactive management tools

Table of Content
----------------

[](#table-of-content)

- [How it works ?](#how-it-works)
- [Installation](#installation)
- [Configuration](#configuration)
    - [Prepare Symfony](#prepare-symfony)
    - [Add PhpRbac configuration](#add-phprbac-configuration)
    - [Cache Configuration](#cache-configuration)
    - [Roles and permissions creation](#roles-and-permissions-creation)
    - [Make the rbac relations](#make-the-rbac-relations)
    - [Assign Role to the user and check permission](#assign-role-to-the-user-and-check-permission)
- [RBAC for controller](#rbac-for-controller)
- [Voter based RBAC](#voter-based-rbac)
- [Cache System](#cache-system)
- [Symfony CLI commands](#symfony-cli-commands)
- [Twig functions](#twig)
- [Documentation](#documentation)

How it works ?
--------------

[](#how-it-works-)

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

[![Roles and Permissions](https://camo.githubusercontent.com/ed588afa9b72c409264b2e022943fc0e1488e87e945e2205238a19b53dbcbc4a/68747470733a2f2f706870726261632e6e65742f696d672f726261632e706e67)](https://camo.githubusercontent.com/ed588afa9b72c409264b2e022943fc0e1488e87e945e2205238a19b53dbcbc4a/68747470733a2f2f706870726261632e6e65742f696d672f726261632e706e67)

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

[](#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
-------------

[](#configuration)

### Prepare Symfony

[](#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

[](#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('rbac_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('rbac_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
  cache:
    enabled: true    # Enable cache for better performance
    ttl: 3600       # Cache TTL in seconds (1 hour)
    prefix: 'rbac_' # Cache key prefix
```

### Cache Configuration

[](#cache-configuration)

The bundle includes a powerful caching system that reduces database queries by 80-90%. The cache is enabled by default.

**Configuration options:**

- `enabled`: Enable or disable the cache (default: `true`)
- `ttl`: Cache time-to-live in seconds (default: `3600` - 1 hour)
- `prefix`: Cache key prefix to avoid collisions (default: `'rbac_'`)

**Environment-specific configuration:**

```
# config/packages/prod/php_rbac.yaml
php_rbac:
    cache:
        enabled: true
        ttl: 7200  # 2 hours in production

# config/packages/dev/php_rbac.yaml
php_rbac:
    cache:
        enabled: false  # Disable in development for easier debugging
```

For more details, see the [Cache Documentation](docs/CACHE.md).

### Roles and permissions creation

[](#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
-----------------------

[](#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

[](#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
-------------------

[](#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
----------------

[](#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
```

Cache System
------------

[](#cache-system)

The bundle includes a high-performance caching system that dramatically reduces database queries.

### Clear Cache Commands

[](#clear-cache-commands)

```
# Clear all RBAC cache
php bin/console security:rbac:cache:clear

# Clear only permissions cache
php bin/console security:rbac:cache:clear --permissions

# Clear only roles cache
php bin/console security:rbac:cache:clear --roles

# Clear cache for specific user
php bin/console security:rbac:cache:clear --user=42
```

### Performance Impact

[](#performance-impact)

- **80-90% reduction** in database queries
- First check: 15ms (DB + cache)
- Subsequent checks: 0.5ms (cache only)
- Over 100 checks: 1500ms → 65ms (95.7% faster)

For complete cache documentation, see [docs/CACHE.md](docs/CACHE.md).

Symfony CLI commands
--------------------

[](#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
```

Clear RBAC cache

```
security:rbac:cache:clear
```

Theses commandes are interactives.

Twig
----

[](#twig)

test if user has a role

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

test if user has a permission

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

Documentation
-------------

[](#documentation)

- **[Cache System](docs/CACHE.md)** - Complete cache documentation

Requirements
------------

[](#requirements)

- PHP 8.3 or higher
- Symfony 7.3 or higher
- Doctrine ORM 3.3 or higher
- MySQL 5.7+, MariaDB 10.2+, or PostgreSQL 12+

License
-------

[](#license)

This bundle is released under the MIT License. See the [LICENSE](LICENSE) file for details.

###  Health Score

50

—

FairBetter than 96% of packages

Maintenance68

Regular maintenance activity

Popularity36

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 68% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~88 days

Recently: every ~80 days

Total

17

Last Release

105d ago

Major Versions

v0.5.1 → v1.0.12024-09-12

1.1.2 → 7.0.x-dev2026-02-03

PHP version history (3 changes)v0.0.1PHP ^8.0

v1.0.1PHP ^8.1

7.3.x-devPHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/6ca7a9937eb4a7f77b158fcd9f6ac78e987c36bafb50bd7173a5bd11ecb7d5d7?d=identicon)[ofouache](/maintainers/ofouache)

---

Top Contributors

[![Olivier127](https://avatars.githubusercontent.com/u/70262207?v=4)](https://github.com/Olivier127 "Olivier127 (34 commits)")[![birkof](https://avatars.githubusercontent.com/u/65848?v=4)](https://github.com/birkof "birkof (7 commits)")[![Myks92](https://avatars.githubusercontent.com/u/31630905?v=4)](https://github.com/Myks92 "Myks92 (5 commits)")[![zpottie](https://avatars.githubusercontent.com/u/9076608?v=4)](https://github.com/zpottie "zpottie (2 commits)")[![anthony-321](https://avatars.githubusercontent.com/u/163052398?v=4)](https://github.com/anthony-321 "anthony-321 (1 commits)")[![bazo](https://avatars.githubusercontent.com/u/181588?v=4)](https://github.com/bazo "bazo (1 commits)")

---

Tags

access-controlaccess-managementaclauthorizationpermissionpermissionsphpphprbacrbacsecuritysymfony-bundlesymfony6symfonybundlesecurityrbacowaspaccess-controlrolephprbac.net

### Embed Badge

![Health badge](/badges/olivier127-rbac-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/olivier127-rbac-bundle/health.svg)](https://phpackages.com/packages/olivier127-rbac-bundle)
```

###  Alternatives

[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[scheb/2fa

Two-factor authentication for Symfony applications (please use scheb/2fa-bundle to install)

578630.7k1](/packages/scheb-2fa)[web-auth/webauthn-framework

FIDO2/Webauthn library for PHP and Symfony Bundle.

50570.7k1](/packages/web-auth-webauthn-framework)[web-auth/webauthn-symfony-bundle

FIDO2/Webauthn Security Bundle For Symfony

63397.4k6](/packages/web-auth-webauthn-symfony-bundle)[ahmed-bhs/doctrine-doctor

Runtime analysis tool for Doctrine ORM integrated into Symfony Web Profiler. Unlike static linters, it analyzes actual query execution at runtime to detect performance bottlenecks, security vulnerabilities, and best practice violations during development with real execution context and data.

813.1k](/packages/ahmed-bhs-doctrine-doctor)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
