Download the PHP package fedale/access-control-voter-bundle without Composer
On this page you can find all versions of the php package fedale/access-control-voter-bundle. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download fedale/access-control-voter-bundle
More information about fedale/access-control-voter-bundle
Files in fedale/access-control-voter-bundle
Package access-control-voter-bundle
Short Description Symfony RBAC bundle inspired by Yii2 (auth_item / auth_item_child / auth_assignment / auth_rule): roles, permissions, hierarchy, per-user assignments and contextual rules, with a can() API and DB-driven role hierarchy
License MIT
Informations about the package access-control-voter-bundle
Fedale RBAC Bundle
A Symfony RBAC bundle inspired by Yii2's auth manager. It mirrors a four-table
model (auth_item, auth_item_child, auth_assignment, auth_rule) and maps
those concepts onto native Symfony primitives. It adds a can() API for
permissions alongside isGranted() for roles, a DB-driven role hierarchy, and
contextual rules (service- or expression-based).
Not to be confused with
fedale/access-control-bundle, which is the perimeter HTTP guard (path/host/IP firewall). This bundle is RBAC authorization (roles/permissions/hierarchy/rules) and is fully independent.
Concept mapping
| Yii2 RBAC | Here |
|---|---|
auth_item (role/permission, type field) |
auth_item table + AuthItemType enum (role/permission) |
auth_item_child (parent→child hierarchy) |
auth_item_child table (role→role, role→permission, permission→permission) |
auth_assignment (user→item) |
auth_assignment table (role or permission, including direct-to-user) |
auth_rule (execute()) |
auth_rule table + RuleInterface / ExpressionRule |
Yii::$app->user->can($item, $params) |
AccessManagerInterface::can($item, $subject) |
| role→role hierarchy | RbacRoleHierarchy decorating security.role_hierarchy |
The key expressiveness: you can assign a permission directly to a single
user (via auth_assignment), bypassing the hierarchy — something Symfony's
roles-only model does not support natively.
Architecture
- Assignment (user→item):
auth_assignment, the single source of truth (see Token integration). - Role→role hierarchy:
RbacRoleHierarchyfeedsisGranted(ROLE_*). - Permissions / decision:
AccessManager::can($item, $subject)walks upauth_item_childgating each node with itsauth_rule. It is also exposed throughDynamicVoter, so#[IsGranted('PERMISSION', subject: $obj)]andisGranted('PERMISSION', $obj)keep working.
can() accepts any item (role or permission). Recommended convention:
isGranted(ROLE) for a plain role check; can(item, $subject) when you need a
rule's contextual gating.
RBAC model & NIST positioning
In NIST RBAC (ANSI INCITS 359) terms the bundle covers:
- Core RBAC (L1) — users, roles, permissions; permissions acquired through roles,
plus direct permission-to-user assignment (
auth_assignmentaccepts a permission, not only a role). - Hierarchical RBAC (L2), general —
auth_item_childis an arbitrary DAG with multiple inheritance (role→role, role→permission, permission→permission), not limited to a tree. - Beyond static RBAC —
auth_ruleadds contextual, object-level conditions (service- or expression-based on the$subject), an ABAC-style capability that plain RBAC lacks.
Not implemented: Separation of Duty (Constrained RBAC, L3) — mutually-exclusive roles (SSD/DSD) and role cardinality are out of scope.
Installation
Register the bundle (usually automatic with Flex):
With the Doctrine provider (default) the entities' ORM mapping is registered
automatically: you don't need to add doctrine.orm.mappings entries.
Configuration
Database schema (Doctrine provider)
The four tables (FK constraints as shown):
Generate the migration with php bin/console doctrine:migrations:diff after
installing the bundle.
Notes: a rule references a service_id or an expression (no serialized PHP
object); timestamps are DATETIME; user_id is VARCHAR(255).
Token integration
auth_assignment is the single source of truth for user→item. For
isGranted(ROLE_*) to reflect assigned roles, choose one mechanism:
Primary (recommended): User::getRoles() reads auth_assignment
The User entity implements AssignedRolesAwareInterface; the
AssignedRolesUserProvider decorator injects the roles on every load/refresh
(token always fresh, no session lag).
Fallback: inject_assigned_roles: true
For apps that cannot modify the User class. A listener on
AuthenticationTokenCreatedEvent enriches the token (handles the standard
login's PostAuthenticationToken). With stateful firewalls the injected roles
stay in the session token until re-login; can() always reads fresh anyway.
Migrating from an existing user_role_assigned table
If your app already stores role assignments in its own table, migrate them into
auth_assignment and drop it:
DB-driven role hierarchy
With override_role_hierarchy: true the bundle decorates
security.role_hierarchy with RbacRoleHierarchy, which expands the role→role
edges from auth_item_child (transitive closure). It replaces the
security.yaml role_hierarchy: any static edges defined there must be
mirrored in auth_item_child. Permissions do not enter the role hierarchy
(they are resolved by can()).
isGranted(ROLE_*) is answered by the bundle's RbacRoleVoter, which replaces
Symfony's RoleVoter/RoleHierarchyVoter: Symfony registers only the plain
RoleVoter when security.yaml has no role_hierarchy, and that one never reads
the hierarchy.
Rules (auth_rule)
A rule attached to an item via rule_name runs during can() (node gate). Two
forms, both stored in the DB:
Service rule (service_id)
auth_rule.service_id = 'App\Security\AuthorRule'. A service rule can also
delegate to one of your own voters: $this->security->isGranted('MY_ATTR', $params).
Expression rule (expression)
An ExpressionLanguage string in auth_rule.expression, evaluated by
ExpressionRule. Variables: user, token, subject (the $subject of
can(), which may be a map), item, roles, auth_checker (for
is_granted(...)), tenant (the current tenant id, global without tenancy). Examples:
With
#[IsGranted], theattributeExpression is the condition (→auth_rule.expression); thesubject:part that usesargs[...]stays in the controller attribute and produces the$subjectthat reaches the rule.
Usage
In Twig (when twig/twig is installed) the can() function mirrors the PHP API;
native is_granted('ROLE_X') still covers plain role checks:
Your own voters coexist with DynamicVoter (which abstains on non-permission
attributes); use disjoint attributes to avoid double votes.
Management (write API)
With the Doctrine provider the bundle exposes a write API to manage the graph,
RbacManagerInterface. Every mutation flushes and invalidates the affected cache.
CLI equivalents (Doctrine provider):
assign/revoke use the value returned by getUserIdentifier() as user_id.
The write API invalidates the cache automatically. When you seed the tables out-of-band (SQL/fixtures), clear the bundle's cache keys explicitly (only the RBAC keys, not the whole pool; available when the cache is enabled):
Writes inside a database transaction are safe to roll back. While the connection
has a transaction open, the item graph and the rules are read from the database
on every call and never cached (TransactionCacheWriteGuard): a read there sees
the transaction's own writes, and a rollback would otherwise leave items in the
cache that were never committed. So an app can create items inside its own
transaction (the permissions of a new record type, created with it) and roll the
whole thing back. The graph is rebuilt on each read meanwhile, so keep such
transactions short.
A custom cache setup can pass its own CacheWriteGuardInterface as the last
argument of CachedItemStorage and CachedRuleStorage.
Multi-tenancy
Two setups are supported. Both start from a TenantContextInterface that tells
the bundle the tenant of the current decision; it is read on every
can()/isGranted(), so the tenant can come from the request (host, route,
header) and change from one request to the next.
The id global (TenantContextInterface::GLOBAL) is reserved. Without a
tenancy.context the bundle uses GlobalTenantContext, which always answers
global: a single-tenant app sees no difference.
Tables per tenant (schema or database per tenant)
Each tenant has its own auth_* tables, and the app points the connection at the
current tenant's (e.g. PostgreSQL search_path). Roles and permissions belong to
the tenant. Only the context is needed:
The bundle then keeps the cache per tenant: fedale_rbac.items.<tenant>, and the
rule keys likewise (the global tenant keeps the unsuffixed keys). The
in-memory graph, the role-hierarchy memo and the per-request memo of the
assignments are per tenant too, so a worker or a command switching tenant does
not see the previous tenant's graph or assignments. The write API
and rbac:cache:clear invalidate the current tenant's keys; the write API also
resets everything kept in memory (graphs, rules, role hierarchy, assignments),
as kernel.reset does between two requests of a worker.
Shared tables, assignments per tenant
One set of roles and permissions for every tenant; what changes is who has what:
a user may be ROLE_ADMIN in acme and ROLE_VIEWER in globex.
- Every assignment has a
tenant_id. An assignment inglobalapplies in every tenant (e.g. a platform admin); the others only in their tenant. can()seeds from the global assignments plus the current tenant's.- The token holds the global roles only (
AssignmentRolesProvider,AssignedRolesUserProvider): they do not depend on the request, so the token does not change when the tenant does. Symfony logs a user out when the refreshed user's roles differ from the token's. RbacRoleVoteradds the current tenant's roles toisGranted(ROLE_*)at decision time, through the role hierarchy. Code reading$token->getRoleNames()(or therolesvariable of an expression rule) sees the global roles only: check withisGranted().assign()andrevoke()take the tenant;revoke()removes the assignment of exactly that tenant.rbac:assign,rbac:revoke,rbac:list-assignmentsandrbac:checkget an--assignment-tenantoption, defaulting to the current tenant. It is not called--tenantso as not to clash with an app's own global--tenantoption.
Expression rules get a tenant variable in both setups, e.g.
subject.getTenantId() == tenant.
Isolating the data itself (one tenant's records never reaching another) is the app's job, e.g. with a Doctrine filter; RBAC only answers "may this user, in this tenant, do this?".
Upgrading an existing installation
- Doctrine provider:
auth_assignmentgainstenant_id(default'global', so existing rows stay global) and its primary key becomes(item_name, user_id, tenant_id). Generate the migration withdoctrine:migrations:diff. - Custom providers:
AssignmentStorageInterface::getAssignments()takes a second argument,string $tenantId = TenantContextInterface::GLOBAL.
Custom provider (no Doctrine)
Set provider: to anything other than doctrine and register services for the
three interfaces ItemStorageInterface, AssignmentStorageInterface,
RuleStorageInterface. The rest of the bundle (AccessManager, role hierarchy,
voter, rule resolver) is source-agnostic. The write API and management commands
are Doctrine-only; a custom provider can implement RbacManagerInterface itself.
Read-only commands
With tenancy.scoped_assignments, both take --assignment-tenant=<id>.
Tests
All versions of access-control-voter-bundle with dependencies
psr/cache Version ^3.0
psr/container Version ^1.1 || ^2.0
symfony/config Version ^6.4 || ^7.0 || ^8.0
symfony/console Version ^6.4 || ^7.0 || ^8.0
symfony/dependency-injection Version ^6.4 || ^7.0 || ^8.0
symfony/expression-language Version ^6.4 || ^7.0 || ^8.0
symfony/http-kernel Version ^6.4 || ^7.0 || ^8.0
symfony/security-core Version ^6.4 || ^7.0 || ^8.0
symfony/security-bundle Version ^6.4 || ^7.0 || ^8.0
symfony/security-http Version ^6.4 || ^7.0 || ^8.0
symfony/service-contracts Version ^2.5 || ^3.0