Authorization in DDD
Where does the question “may this user do this?” belong – in the controller, in a voter, or in the aggregate? The chapter breaks it down into four layers: Edge, Use Case, Aggregate, and Field. Each answers a different question and has its own tool in Symfony.
In this chapter
The previous chapter, Implementation in Symfony 8, built aggregates, repositories, and Application Services in Symfony 8. It deliberately left authorization aside, which left open a question that projects usually settle case by case: who may call which use case, and under what conditions. The answer is a four-layer framework that places every authorization decision on exactly one layer: from the HTTP firewall, through a Symfony Voter that the application layer calls from the handler, down to the domain invariants in the aggregate. The call from the Command Handler is shown in section 11.04; the CQRS chapter builds on it with a middleware layer that can move authorization in front of the handler.
Authentication (Symfony firewall, JWT, OAuth) is something most teams build without much trouble. The question “who may do what with a specific entity in a specific state” is a different discipline. Without a framework, the answer scatters across controllers, listeners, Twig templates, and Doctrine query builders. The framework tells you where each rule belongs and how to write it in Symfony 8 so that the Security component does not leak into the domain core.
The chapter continues in CQRS (where the check sits in the Command Handler) and Testing DDD (how to test each of the four layers separately). DDD in Practice – Where It Hurts mentions authorization only in passing.
11.01 Three authorization mistakes that keep showing up in code review#
The three patterns below share one cause: there is no decision framework for where each rule belongs. The order reflects their estimated frequency in code review; there is no measured data behind it, only the author's estimate. That the topic deserves a chapter of its own, however, can be backed up: in the Top 10 for 2021, OWASP moved Broken Access Control from fifth place to first.
Mistake 1: everything in the controller
The most common pattern. The controller receives an HTTP request, loads the entity from the repository, and compares the user's attributes with the entity's attributes inline:
1<?php2 3// src/Controller/OrderController.php (anti-pattern)4namespace App\Controller;5 6use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;7use Symfony\Component\HttpFoundation\Response;8use Symfony\Component\Routing\Attribute\Route;9use App\Ordering\Domain\Repository\OrderRepository;10 11final class OrderController extends AbstractController12{13 #[Route('/order/{id}/cancel', methods: ['POST'])]14 public function cancel(string $id, OrderRepository $orders): Response15 {16 $order = $orders->find($id);17 $user = $this->getUser();18 19 // Anti-pattern: authorization logic scattered across the controller20 if ($user->getId() !== $order->getCustomerId()) {21 throw $this->createAccessDeniedException('Not your order');22 }23 if ($order->getStatus() !== 'placed') {24 throw new \LogicException('Cannot cancel a non-placed order');25 }26 27 $order->setStatus('cancelled');28 $orders->save($order);29 30 return $this->redirectToRoute('order_detail', ['id' => $id]);31 }32}
What is wrong: the same use case is also called from a console command (cron, batch), from a Symfony Messenger handler (an asynchronous queue), and from the admin panel. Every entry point has to repeat the same condition, and it takes only one that forgets. The rule “only the owner may cancel” should have one place of definition and be enforced in the use case, not in each entry point separately.
Mistake 2: everything in the Voter, the domain knows nothing about authorization
The opposite extreme. The team discovers the Symfony Voter and moves all rules into it, domain invariants included. The aggregate has a public API of setStatus(), setTotal(), and setCustomerId(), and the Voter checks the rules from outside, reading the state through the matching getters:
1<?php2 3// src/Security/OrderVoter.php (anti-pattern)4namespace App\Security;5 6use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;7use Symfony\Component\Security\Core\Authorization\Voter\Vote;8use Symfony\Component\Security\Core\Authorization\Voter\Voter;9 10final class OrderVoter extends Voter11{12 protected function voteOnAttribute(13 string $attribute,14 mixed $subject,15 TokenInterface $token,16 ?Vote $vote = null,17 ): bool18 {19 $user = $token->getUser();20 21 // Anti-pattern: a domain rule (the cancellation window) in the Voter22 if ($attribute === 'CANCEL') {23 if ($user->getId() !== $subject->getCustomerId()) { return false; }24 if ($subject->getStatus() !== 'placed') { return false; }25 $age = (new \DateTimeImmutable())->getTimestamp() - $subject->getPlacedAt()->getTimestamp();26 if ($age > 86400) { return false; }27 return true;28 }29 return false;30 }31}
What is wrong: the setter Order::setStatus('cancelled') still exists and is public. All it takes is for anyone (a test, a fixture, a migration script, another developer) to call it outside the Voter, and the invariant “cancellation within 24 h” stops holding. The Voter is only an optional filter at the entrance; the domain has no safeguard of its own. The cancellation window is a domain rule, not a use-case rule.
Mistake 3: authorization at the database row level
The team discovers the Doctrine SQLFilter and decides to solve authorization in the persistence layer: entities the user has no access to are never returned from the database. For read queries this works; in domain logic it does not:
- When a handler receives an
$orderIdand cannot find the entity, it does not know whether the entity does not exist or is only unavailable to the given user. The message “Order not found” then misleads. - Doctrine filters do not apply to entities already loaded into the identity map, to native SQL, or to a Redis cache.
- Nor does the filter apply when loading the inverse side of a one-to-one association. Verified on ORM 3.6:
find()and DQL both hide a foreign record, but navigating from the entity to the other end of the relationship returns it. Anyone who builds tenant separation on the filter alone has a hole here. - Domain rules such as “an order belongs to a customer” lose their single authoritative place: they are written in the SQL filter, forgotten in the Voter, and missing from the aggregate. When called outside the HTTP layer, they are not enforced.
11.02 Four layers of authorization#
First, the strategic context. Identity and permissions form a Bounded Context of their own, which Vernon calls the Identity and Access Context in Implementing Domain-Driven Design. In the IDDD_Samples reference implementation, it stands as a separate module next to Collaboration and Agile PM, and the other contexts consume it as a service. In terms of subdomain type, it is a Generic Subdomain: it is bought (Keycloak, Auth0, an OIDC provider), not modeled in-house. The authorization decision, however, stays in the consuming context, because it depends on that context's entities and states. The source of identities and roles lies outside it, and Context Mapping describes the link between the two as an Open Host Service.
Inside the consuming context, the decision is made in four successive layers. Each has its own question, Symfony tool, and granularity. The layers act as filters: each next one answers a finer question and assumes that the previous one has already said “yes.”
| Layer | Question | Symfony tool | Example |
|---|---|---|---|
| Edge | Is the user logged in? May they access this URL? | access_control, JWT firewall |
/admin/* only for ROLE_ADMIN |
| Use Case | May they execute the use case on this object? | Voter |
“May Petr cancel order #42?” |
| Aggregate | Can it be done at all right now? | domain check + exception | “An order can be cancelled only within 24 h of confirmation” |
| Field | May they see a specific field? | Twig + Voter, query filter | “Only an admin sees the audit_log column” |
Every authorization rule has exactly one place of definition. It can be enforced on several layers, as long as all of them read the same definition. OWASP phrases this as a requirement to implement a check once and reuse it. Duplication begins only with rewriting the same rule in other words on another layer; the typical cases are shown in the Anti-patterns section.
The filter metaphor has one condition. Inside the use-case layer, it holds only with the unanimous decision strategy. The default affirmative reverses it: one approving Voter is enough, and the disagreement of the others is ignored. Details in the Decision strategy and AccessDecisionManager section.
Citations: the Symfony Security component documents the multi-layer approach in its “Authorization” section [1]; the general principles of ABAC vs. RBAC are in NIST SP 800-162 [2]. In Implementing Domain-Driven Design (chapter 14, “Application”), Vernon places the authorization check in Application Services: in his view, the application service takes care of security and object translation. You will not find the four-layer framework of this chapter in his book – it is the author's extension, not Vernon's model.
11.03 Edge – Symfony firewall and access_control#
Edge is the coarsest layer and lies outside the domain code. It answers only the question “who is on the other end of the socket at all?”: anonymous, logged in, possibly with a role for coarsely divided sections (/admin/*, /api/v1/*). Rules such as “customer X may access this order” belong one layer up (use case).
The user provider points to the SecurityUser class from the infrastructure, not to a domain entity. The rest of the chapter rests on this: the provider requires an implementation of Symfony\Component\Security\Core\User\UserInterface, and if a domain class carried it, the domain would be tied to the Security component. That is exactly what anti-pattern 4 forbids. SecurityUser is also a read model for authentication: it carries the identifier, the password hash, the roles, and the domain ID (CustomerId, TenantId). It changes for different reasons than the domain model of the user [3].
1# config/packages/security.yaml2security:3 # The security-bundle recipe generates this block itself. If you copy4 # the listing below as the whole file, you lose it – and the first login5 # then ends with “No password hasher has been configured”.6 password_hashers:7 Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'8 9 providers:10 app_user_provider:11 entity:12 # An infrastructure class implementing UserInterface,13 # mapped to the app_user table. The domain does not know it.14 class: App\Identity\Infrastructure\Security\SecurityUser15 property: email16 17 firewalls:18 # Stateless API – JWT. The `jwt` key is registered by19 # lexik/jwt-authentication-bundle; without it the configuration fails20 # (“Unrecognized option jwt”), so keep the whole block commented out21 # until you have the bundle. The native equivalent is `access_token`.22 # api:23 # pattern: ^/api/24 # stateless: true25 # jwt: ~26 # provider: app_user_provider27 28 # Web – session29 main:30 pattern: ^/31 lazy: true32 provider: app_user_provider33 form_login:34 login_path: login35 check_path: login36 # The template sends `_csrf_token` with the id `authenticate`,37 # but without this option form_login neither reads nor checks it.38 enable_csrf: true39 # Without this line, Symfony redirects to `/` after login,40 # which the book defines nowhere – the first click after login41 # would end in a 404.42 default_target_path: app_profile43 # Without `target`, the same applies as for login: logout44 # redirects to `/` and ends in a 404.45 logout: { target: login }46 47 access_control:48 # Public endpoints49 - { path: ^/login, roles: PUBLIC_ACCESS }50 # Mind the path shape: ^/register does not cover /api/register.51 # The JSON endpoint would otherwise end in a redirect to login before52 # the controller even runs.53 - { path: ^/register, roles: PUBLIC_ACCESS }54 - { path: ^/api/register, roles: PUBLIC_ACCESS }55 - { path: ^/health, roles: PUBLIC_ACCESS }56 # Coarse role-based separation57 - { path: ^/admin, roles: ROLE_ADMIN }58 - { path: ^/api/internal, roles: ROLE_SERVICE_ACCOUNT }59 # Everything else behind authentication60 - { path: ^/, roles: IS_AUTHENTICATED_FULLY }
form_login refers to the login route. The firewall does not create it, and the first protected request
fails on the missing route:
1<?php2 3declare(strict_types=1);4 5namespace App\Identity\Infrastructure\Http;6 7use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;8use Symfony\Component\HttpFoundation\Response;9use Symfony\Component\Routing\Attribute\Route;10use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;11 12final class LoginController extends AbstractController13{14 // The firewall handles the login itself. The controller only renders15 // the form and the last error – that is why there is no logic here.16 #[Route('/login', name: 'login', methods: ['GET', 'POST'])]17 public function __invoke(AuthenticationUtils $utils): Response18 {19 return $this->render('security/login.html.twig', [20 'last_username' => $utils->getLastUsername(),21 'error' => $utils->getLastAuthenticationError(),22 ]);23 }24}
The template is short, but two names in it are not free to choose: _username and _password are expected by
the form_login authenticator, and renaming them means reconfiguring the firewall.
1{% extends 'base.html.twig' %}2 3{% block body %}4 {% if error %}5 <p class="error">{{ error.messageKey|trans(error.messageData, 'security') }}</p>6 {% endif %}7 8 <form method="post">9 <label for="username">Email</label>10 <input type="email" id="username" name="_username" value="{{ last_username }}" required>11 12 <label for="password">Password</label>13 <input type="password" id="password" name="_password" required>14 15 <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">16 <button type="submit">Log in</button>17 </form>18{% endblock %}
The SecurityUser class forms the bridge between Symfony and the domain. Besides UserInterface, it exposes domain identifiers for the application layer:
1<?php2 3// src/Identity/Infrastructure/Security/SecurityUser.php4declare(strict_types=1);5 6namespace App\Identity\Infrastructure\Security;7 8use App\Ordering\Domain\ValueObject\CustomerId;9use App\Identity\Domain\TenantId;10use Doctrine\ORM\Mapping as ORM;11use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;12use Symfony\Component\Security\Core\User\UserInterface;13 14#[ORM\Entity]15#[ORM\Table(name: 'app_user')]16class SecurityUser implements UserInterface, PasswordAuthenticatedUserInterface17{18 public function __construct(19 #[ORM\Id, ORM\Column(type: 'string')]20 private string $email,21 #[ORM\Column(type: 'string')]22 private string $passwordHash,23 /** @var list<string> */24 #[ORM\Column(type: 'json')]25 private array $roles,26 #[ORM\Column(type: 'string')]27 private string $customerId,28 #[ORM\Column(type: 'string')]29 private string $tenantId,30 ) {}31 32 public function getUserIdentifier(): string { return $this->email; }33 public function getPassword(): string { return $this->passwordHash; }34 35 /** @return list<string> */36 public function getRoles(): array { return $this->roles; }37 38 // Bridge to the domain – both the Voter and the handler work with the domain type39 public function customerId(): CustomerId { return CustomerId::fromString($this->customerId); }40 public function tenantId(): TenantId { return TenantId::fromString($this->tenantId); }41}
TenantId is an ordinary value object of the same shape as OrderId; without it, SecurityUser
does not even get through the autoloader, and the firewall is left without users:
1<?php2 3declare(strict_types=1);4 5namespace App\Identity\Domain;6 7final readonly class TenantId8{9 public function __construct(10 public string $value,11 ) {12 if ($value === '') {13 throw new \InvalidArgumentException('TenantId must not be empty.');14 }15 }16 17 public static function fromString(string $value): self18 {19 return new self($value);20 }21 22 public function __toString(): string23 {24 return $this->value;25 }26}
Principles of the edge layer:
- No domain knowledge. Edge does not know the concepts “order,” “customer,” or “cancellation window.” It works only with URL patterns, roles, and the authentication state.
- Default deny. The last rule in
access_controlis “everything else requires login.” Without it, adding a new endpoint and forgetting to classify it is enough to make it public. - Role-based, not attribute-based. ROLE_ADMIN is a coarse category; finer decisions such as “admin of tenant T1, not T2” belong in the Voter.
- JWT firewall vs. session. An API tends to be stateless (the
jwtauthenticator), the web works with a session. For JWT in Symfony, there is thelexik/jwt-authentication-bundlepackage or the nativeaccess_tokenauthenticator withOidcTokenHandlerfor an OpenID Connect provider [4].
access_control has more matchers than path and roles. Available are host, port, ips, methods, attributes, route, and request_matcher, plus allow_if and requires_channel [5]. The first matching rule applies, and an unspecified matcher matches anything. A rule { path: ^/api, methods: [POST] } therefore does not protect GET on the same path, unless a more general entry comes earlier in the list.
11.04 Use Case – Symfony Voter#
The use-case layer answers the question “may this user execute this use case on this object?”. That is exactly what the Symfony Voter is designed for. The rule: 1 use case = 1 Voter attribute; one Voter can cover N attributes if they concern the same entity (typically operations on one aggregate).
A Voter knows two things: the user's identity (through TokenInterface) and the target subject (typically the aggregate root). It must not load the subject it decides about, and it must not know domain invariants – the aggregate enforces those. The Voter therefore does not take over the cancellation window from outside; it belongs to the aggregate's state.
1<?php2 3// src/Ordering/Infrastructure/Security/OrderVoter.php4declare(strict_types=1);5 6namespace App\Ordering\Infrastructure\Security;7 8use App\Identity\Infrastructure\Security\SecurityUser;9use App\Ordering\Domain\Model\Order;10use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;11use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;12use Symfony\Component\Security\Core\Authorization\Voter\Vote;13use Symfony\Component\Security\Core\Authorization\Voter\Voter;14 15final class OrderVoter extends Voter16{17 public const VIEW = 'order.view';18 public const CANCEL = 'order.cancel';19 public const REFUND = 'order.refund';20 21 public function __construct(22 private readonly AccessDecisionManagerInterface $decisions,23 ) {}24 25 protected function supports(string $attribute, mixed $subject): bool26 {27 return in_array($attribute, [self::VIEW, self::CANCEL, self::REFUND], true)28 && $subject instanceof Order;29 }30 31 public function supportsAttribute(string $attribute): bool32 {33 return in_array($attribute, [self::VIEW, self::CANCEL, self::REFUND], true);34 }35 36 public function supportsType(string $subjectType): bool37 {38 return $subjectType === Order::class;39 }40 41 protected function voteOnAttribute(42 string $attribute,43 mixed $subject,44 TokenInterface $token,45 ?Vote $vote = null,46 ): bool47 {48 $user = $token->getUser();49 if (!$user instanceof SecurityUser) {50 return false;51 }52 53 \assert($subject instanceof Order);54 55 return match ($attribute) {56 self::VIEW => $this->canView($subject, $user, $token),57 self::CANCEL => $this->canCancel($subject, $user),58 self::REFUND => $this->decisions->decide($token, ['ROLE_REFUND_AGENT']),59 default => false,60 };61 }62 63 private function canView(Order $order, SecurityUser $user, TokenInterface $token): bool64 {65 // The aggregate defines ownership, the Voter only asks66 return $order->isOwnedBy($user->customerId())67 || $this->decisions->decide($token, ['ROLE_ADMIN']);68 }69 70 private function canCancel(Order $order, SecurityUser $user): bool71 {72 return $order->isOwnedBy($user->customerId());73 }74}
Five implementation details:
- Attribute constants prefixed with the entity (
order.cancel, not justCANCEL). They do not collide with the attributes of other Voters (invoice.cancel,shipment.cancel), and the audit log shows at a glance which subject the decision concerned. - A match expression instead of an if-else tree. Without a default arm, PHPStan reports an unhandled case;
default => falseopts for silent denial (fail-closed) and sacrifices this check. - Private methods
canViewandcanCancel. Each use case has its own method, and a test verifies the result of each one separately. Without the extraction, the Voter would grow into an unreadable switch-case. - Roles inside the Voter are checked through
AccessDecisionManagerInterface::decide(), not by asking the user class. The checkin_array('ROLE_ADMIN', $user->getRoles(), true)bypasses the role hierarchy fromsecurity.yaml: a user withROLE_SUPER_ADMINwould not getROLE_ADMIN, even though the hierarchy includes it. The Security documentation warns against a manualgetRoles()[1], and the Voters documentation recommendsdecide()inside a Voter [7]. supportsAttribute()andsupportsType()come fromCacheableVoterInterface, which the abstractVoterimplements. Both returntrueby default, so without an override they save nothing. A list with 200 rows and five Voters means a thousand unnecessarysupports()calls; with the override, most of them are dropped already in the decision manager.
Decision strategy and AccessDecisionManager
An application usually has several Voters, and the AccessDecisionManager combines their votes. The strategy it uses changes the result more than anything inside the Voters themselves:
| Strategy | Behavior | When it fits |
|---|---|---|
affirmative |
default; one approval is enough | simple applications with one Voter per subject |
unanimous |
denies as soon as anyone disagrees | layered authorization, multi-tenancy |
consensus |
the majority decides | rarely; the result is harder to justify |
priority |
the first non-abstaining voter decides | explicit order through #[AsTaggedItem(priority: …)] |
For the framework of this chapter, the default affirmative is the wrong choice. Anyone who builds a TenantVoter next to OrderVoter gets the opposite of what they expected: TenantVoter denies a foreign tenant, OrderVoter says yes based on ownership, and access goes through. Layered authorization therefore needs unanimous.
The block belongs in the same security.yaml as the firewall above, not in place of it. YAML has a single root key security:, and a second document would overwrite the first.
1# config/packages/security.yaml2security:3 access_decision_manager:4 strategy: unanimous5 allow_if_all_abstain: false # nobody voted = denied
The value allow_if_all_abstain: false is the default, but it belongs in the configuration explicitly. It is the last fail-closed safeguard: an attribute that no Voter claims ends in denial, not in silent permission.
#[IsGranted] on the controller
The check in the handler is the authoritative one. At the HTTP boundary, though, it pays to reject a request before a command is even created. That is what the Symfony\Component\Security\Http\Attribute\IsGranted attribute is for. It works on a method as well as on a whole controller class, and its subject parameter determines which action argument the decision is about:
1<?php2 3// src/Ordering/Infrastructure/Http/OrderController.php4declare(strict_types=1);5 6namespace App\Ordering\Infrastructure\Http;7 8use App\Ordering\Application\Command\CancelOrder;9use App\Ordering\Domain\Model\Order;10use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;11use Symfony\Component\HttpFoundation\Request;12use Symfony\Component\HttpFoundation\Response;13use Symfony\Component\Messenger\MessageBusInterface;14use Symfony\Component\Routing\Attribute\Route;15use Symfony\Component\Security\Http\Attribute\IsGranted;16 17#[IsGranted('IS_AUTHENTICATED_FULLY')]18final class OrderController extends AbstractController19{20 #[Route('/order/{id}/cancel', name: 'order_cancel', methods: ['POST'])]21 #[IsGranted('order.cancel', subject: 'order', statusCode: 404)]22 public function cancel(Order $order, Request $request, MessageBusInterface $bus): Response23 {24 // The Voter has already decided; the controller only translates input into a command25 $bus->dispatch(new CancelOrder(26 orderId: $order->id,27 reason: (string) $request->request->get('reason', ''),28 actorId: $this->getUser()->customerId(),29 ));30 31 return $this->redirectToRoute('order_detail', ['id' => $order->id->value]);32 }33 34 #[Route('/order/{id}', name: 'order_detail', methods: ['GET'])]35 #[IsGranted('order.view', subject: 'order', statusCode: 404)]36 public function detail(Order $order): Response37 {38 // isCancellable() does not take the current time by itself, so the template39 // has to get it from here – otherwise Twig reports that the variable does not exist.40 return $this->render('order/detail.html.twig', [41 'order' => $order,42 'now' => new \DateTimeImmutable(),43 ]);44 }45}
The statusCode: 404 parameter changes the response from 403 to 404. The difference is not cosmetic: a 403 confirms to an attacker that an order with the given ID exists and opens the way to enumerating foreign identifiers. The topic is expanded in the 403 vs. 409: which error when? callout.
The attribute has two limitations. First: it needs the subject already as an object, so it cannot do without a conversion from the route parameter, and the database query moves into the controller. #[MapEntity] alone is not enough for that. EntityValueResolver passes the string from the URL to find(), but the identity is mapped with a custom type that rejects a string. The resolver swallows the exception and returns a 404, so the error gets looked for in the wrong place:
Could not convert PHP value '01a074c3-…' to type OrderIdType.
Expected one of the following types: null, OrderId.
The solution is a custom resolver that converts the string into a value object before it touches the repository:
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Infrastructure\Http;6 7use App\Ordering\Domain\Model\Order;8use App\Ordering\Domain\Repository\OrderRepository;9use App\Ordering\Domain\ValueObject\OrderId;10use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;11use Symfony\Component\HttpFoundation\Request;12use Symfony\Component\HttpKernel\Controller\ValueResolverInterface;13use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;14use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;15use Symfony\Component\Uid\Uuid;16 17// Higher priority than EntityValueResolver, otherwise it never gets a turn.18#[AutoconfigureTag('controller.argument_value_resolver', ['priority' => 150])]19final readonly class OrderValueResolver implements ValueResolverInterface20{21 public function __construct(private OrderRepository $orders) {}22 23 public function resolve(Request $request, ArgumentMetadata $argument): iterable24 {25 if ($argument->getType() !== Order::class) {26 return [];27 }28 29 $id = $request->attributes->get('id');30 31 if (!is_string($id) || !Uuid::isValid($id)) {32 throw new NotFoundHttpException('Invalid order ID.');33 }34 35 yield $this->orders->get(OrderId::fromString($id));36 }37}
Second limitation: as soon as the controller merely sends the command to an asynchronous bus, #[IsGranted] protects only the entry into the queue. Processing in the worker runs without a token, and the next section deals with it. The attribute therefore does not replace the check in the handler; it only adds to it at the boundary.
Why not Symfony ACL
Older materials offer the ACL component for permissions on individual objects: the acl_entries and acl_object_identities tables and MaskBuilder. For Symfony 8, it is not an option. ACL support disappeared from SecurityBundle in version 4.0, and the standalone symfony/acl-bundle declares support for Symfony 4.4 through 7.x in its latest release (2.4.0 from April 2024). Symfony 8 is not among them. Nor would it be a good replacement technically. ACL stores decisions as data in the database, so the rule “the owner may cancel within 24 hours” turns into rows that someone has to keep in sync with the aggregate's state. A Voter computes the same thing from the current state and has nothing to synchronize. Where explicitly granted permissions on individual objects are needed (sharing a document, delegation), the tool is a custom link table or the ReBAC model from a later section.
Use in the Command Handler
Someone has to call the Voter. The place for that is the Application Service / Command Handler, where authorization is checked before the domain operation. The handler injects AuthorizationCheckerInterface, an interface of the Security component. Such a dependency is fine in the application layer; the domain must not have it.
1<?php2 3// src/Ordering/Application/Handler/CancelOrderHandler.php4declare(strict_types=1);5 6namespace App\Ordering\Application\Handler;7 8use App\Ordering\Application\Command\CancelOrder;9use App\Ordering\Application\Exception\AccessDeniedDomainException;10use App\Ordering\Domain\Repository\OrderRepository;11use Symfony\Component\Messenger\Attribute\AsMessageHandler;12use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;13 14#[AsMessageHandler(bus: 'command.bus')]15final readonly class CancelOrderHandler16{17 public function __construct(18 private OrderRepository $orders,19 private AuthorizationCheckerInterface $auth,20 ) {}21 22 public function __invoke(CancelOrder $command): void23 {24 $order = $this->orders->get($command->orderId);25 26 // The attribute as a string, the same as in the controller: the constant27 // OrderVoter::CANCEL would tie the handler to the infrastructure.28 if (!$this->auth->isGranted('order.cancel', $order)) {29 throw new AccessDeniedDomainException(30 sprintf('Cancel not allowed for order %s', $command->orderId->value)31 );32 }33 34 $order->cancel(reason: $command->reason, when: new \DateTimeImmutable());35 $this->orders->save($order);36 37 // The example leaves out publishing events to keep the authorization38 // question readable. The async variant below completes it –39 // and without it, the aggregate and the read model drift apart.40 }41}
Both exceptions thrown in this chapter are ordinary classes without framework dependencies. What separates them is the layer: the authorization one belongs to the application, the time window to the domain, and the HTTP layer translates each into a different HTTP status.
1<?php2 3// --- src/Ordering/Application/Exception/AccessDeniedDomainException.php ---4 5declare(strict_types=1);6 7namespace App\Ordering\Application\Exception;8 9/** The actor has no right to the operation. The HTTP layer translates this into 403. */10final class AccessDeniedDomainException extends \DomainException11{12}13 14// --- src/Ordering/Domain/Exception/CancellationWindowExpiredException.php ---15 16namespace App\Ordering\Domain\Exception;17 18use App\Ordering\Domain\ValueObject\OrderId;19 20/** The right is in order, only the window has passed. Hence 409, not 403. */21final class CancellationWindowExpiredException extends \DomainException22{23 public function __construct(24 public readonly OrderId $orderId,25 public readonly \DateTimeImmutable $placedAt,26 public readonly \DateTimeImmutable $attemptedAt,27 ) {28 parent::__construct(sprintf(29 'Order "%s" confirmed at %s can no longer be cancelled (attempted at %s).',30 $orderId->value,31 $placedAt->format('Y-m-d H:i'),32 $attemptedAt->format('Y-m-d H:i'),33 ));34 }35}
After the check, the handler calls the domain operation $order->cancel(...), which verifies the invariants (state, cancellation window) inside the aggregate. This creates two independent barriers: the Voter answers “may Petr do this?”, and the aggregate answers “can this be done right now at all?” The aggregate layer is covered in section 11.06. The catch: the handler carries the #[AsMessageHandler] attribute, and in an asynchronous worker no token exists. The next section deals with that.
Voter in a Twig template
The same Voter also covers decisions in the view, such as hiding the “Cancel order” button from anyone who does not own the order. The is_granted() function in Twig calls the same AuthorizationCheckerInterface. The controller passes the now variable (\DateTimeImmutable) to the template, because isCancellable() does not take the current time by itself. The template reads the aggregate directly, and for the detail of a single order that is enough. As soon as the screen needs the customer's name or data from another context, it should get a read model, not another getter on the aggregate:
1{# templates/order/detail.html.twig #}2{# The template touches only what the aggregate really has: the customer's identity,3 not a Customer object, and the enum value, not an invented label. #}4<h1>Order {{ order.id.value }}</h1>5 6{% if is_granted('order.view', order) %}7 <dl>8 <dt>Customer</dt><dd>{{ order.customerId.value }}</dd>9 <dt>Total</dt> <dd>{{ (order.totalAmount.amountInCents / 100)|number_format(2, ',', ' ') }} CZK</dd>10 <dt>Status</dt> <dd>{{ order.status.value }}</dd>11 </dl>12{% endif %}13 14{% if is_granted('order.cancel', order) and order.isCancellable(now) %}15 <form method="post" action="{{ path('order_cancel', {id: order.id.value}) }}">16 <button type="submit">Cancel order</button>17 </form>18{% endif %}19 20{# Refund is an operation for staff, not for the customer – the attribute lets21 it through only for the role from the Voter. The link points to a route the book22 does not supply, so it is commented out: path() to a nonexistent route breaks the23 whole template, and only once the first user with that role logs in. #}24{# {% if is_granted('order.refund', order) %}25 <a href="{{ path('order_refund', {id: order.id.value}) }}">Refund payment</a>26{% endif %} #}
{% if is_granted(...) %} in Twig only hides the button. It does not stop a request sent by hand (curl, Postman, browser dev tools). The check in the view is UX, not a security barrier; that barrier stands in the handler.
11.06 Aggregate-level – the domain decides for itself#
Some rules do not belong in the Voter. They require knowledge of the domain state, which the Voter should not take over from outside: a time window, the previous state of the order, invariants across entities inside the aggregate. They belong in the aggregate root, which enforces them with a domain exception.
A practical heuristic:
- A rule that requires the state of the aggregate (“the order must not be shipped and must not be older than 24 h”) belongs in the aggregate.
- A rule about the relationship between the actor and the aggregate (ownership, membership, hierarchy) is also defined by the aggregate. The aggregate knows it and keeps knowing it even when the command is processed asynchronously. The Voter asks about it rather than copying it.
- A rule about the attributes of the actor (“only
ROLE_REFUND_AGENTmay refund,” “not outside business hours”) belongs in the Voter. The aggregate knows nothing about roles and should not.
Teams disagree most often on the middle point. “Only the owner may cancel” sounds like a typical use-case rule; in fact, it is an invariant of the relationship between Order and CustomerId. The aggregate therefore answers it with the isOwnedBy() method, and both the Voter and the asynchronous handler call it instead of making their own comparison. The definition stays single; enforcement can happen in both places.
1<?php2 3// An excerpt of the canonical aggregate from the Aggregate Design chapter. It adds only4// what authorization brings; the constructor, factories, and mapping do not change.5declare(strict_types=1);6 7namespace App\Ordering\Domain\Model;8 9use App\Ordering\Domain\Event\OrderCancelled;10use App\Ordering\Domain\Exception\CancellationWindowExpiredException;11use App\Ordering\Domain\Exception\InvalidOrderStateTransitionException;12use App\Ordering\Domain\Exception\OrderLockedBySagaException;13use App\Ordering\Domain\ValueObject\CustomerId;14use App\Ordering\Domain\ValueObject\OrderStatus;15use App\SharedKernel\Domain\AggregateRoot;16 17final class Order extends AggregateRoot18{19 private const CANCELLATION_WINDOW_SECONDS = 86_400; // 24 h20 21 public function cancel(string $reason, \DateTimeImmutable $when): void22 {23 // The lock is held by the process – see the chapter on sagas, the Saga isolation section.24 // This condition is in the canonical version from Aggregate Design too;25 // this listing replaces the method as a whole, not piece by piece.26 if ($this->sagaInProgress) {27 throw new OrderLockedBySagaException($this->id);28 }29 30 // A cancellation cannot bring back a shipped or delivered parcel – that is where31 // compensation in the saga takes over.32 if (in_array($this->status, [OrderStatus::Shipped, OrderStatus::Delivered], true)) {33 throw InvalidOrderStateTransitionException::cannotTransition(34 $this->status->value,35 OrderStatus::Cancelled->value,36 );37 }38 39 // A repeated cancellation is not the caller's error, there is just nothing left to do.40 if ($this->status === OrderStatus::Cancelled) {41 return;42 }43 44 // The window runs from confirmation. A draft does not have one yet, and nobody45 // cancels a cart in progress on a deadline either.46 if ($this->placedAt !== null) {47 $age = $when->getTimestamp() - $this->placedAt->getTimestamp();48 49 if ($age > self::CANCELLATION_WINDOW_SECONDS) {50 throw new CancellationWindowExpiredException(51 $this->id,52 $this->placedAt,53 $when,54 );55 }56 }57 58 $this->status = OrderStatus::Cancelled;59 $this->record(new OrderCancelled(60 orderId: $this->id,61 customerId: $this->customerId,62 reason: $reason,63 occurredAt: $when,64 ));65 }66 67 public function isCancellable(\DateTimeImmutable $now): bool68 {69 // The template asks exactly this method, so it has to know about the lock as well.70 // Otherwise it offers a button whose command ends up in the dead-letter queue.71 if ($this->sagaInProgress) {72 return false;73 }74 75 if (in_array($this->status, [76 OrderStatus::Shipped,77 OrderStatus::Delivered,78 OrderStatus::Cancelled,79 ], true)) {80 return false;81 }82 83 return $this->placedAt === null84 || $now->getTimestamp() - $this->placedAt->getTimestamp()85 <= self::CANCELLATION_WINDOW_SECONDS;86 }87 88 // A relationship invariant: the aggregate knows ownership, not the Voter89 public function isOwnedBy(CustomerId $customerId): bool90 {91 return $this->customerId->equals($customerId);92 }93}
The aggregate has no dependency on Symfony. It uses only standard PHP types and its own domain classes: no TokenInterface, AuthorizationChecker, or UserInterface. That is why it can be tested with a unit test without the Symfony Kernel. It reports failures with the InvalidOrderStateTransitionException and CancellationWindowExpiredException exceptions from App\Ordering\Domain\Exception. They carry domain context (when the order was confirmed, when the cancellation attempt came), and the HTTP layer translates them into 409 Conflict, not 403 Forbidden. This is not an authorization failure; it is a domain state.
The helper method isCancellable() is a query without side effects. The UI uses it to hide the button: the Twig template calls it with the now variable from the controller and combines it with is_granted. It shares the window with cancel() through the CANCELLATION_WINDOW_SECONDS constant, so no duplication arises. What remains are domain events: after a successful operation, the aggregate records OrderCancelled by calling record(), and the handler collects them after repository->save() through releaseEvents() and publishes them (typically through the Outbox). The aggregate itself never calls the EventDispatcher.
Here, the aggregate does not handle the question “may Petr?”; the Voter answered it in section 11.04. The aggregate answers “can it be done right now at all?”, and its “no” holds even when the Voter said “yes”: Petr is the owner, but the order has already shipped. Both barriers are independent, and both are necessary.
cancel() above replaces the version from Aggregate Design as a whole, not piece by piece: it carries the same
state conditions and the lock, and adds the window to them. Only the isCancellable() method is new;
isOwnedBy() is in the listing for completeness and matches the version from Aggregate Design. The constructor,
the factories, and markPaid() stay as Aggregate Design introduces them. The state condition is therefore the same as there: it blocks a shipped and a delivered order, not everything except Confirmed. Narrowing it to Confirmed would look stricter, but it would break compensation: the saga cancels a paid order, the handler would reject the cancellation, and the order would be left hanging.
End-to-end walkthrough: a cancellation request
What happens when the customer Petr clicks “Cancel order #42” in the interface:
- Edge (firewall). Symfony verifies the JWT or the session. Without verification → 401. Petr is logged in, so processing continues.
- Edge (access_control). The URL
/order/42/cancelfalls underIS_AUTHENTICATED_FULLY. Petr is logged in, so processing continues. - Controller validates the input (CSRF token, request body), creates
CancelOrder(orderId: 42, reason: 'changed mind', actorId: <Petr's CustomerId>), and hands it to the message bus. Before that,#[IsGranted(..., statusCode: 404)]has already stopped anyone who does not own the order with a 404. - Application Handler (
CancelOrderHandler) loads the aggregate from the repository:$order = $repo->get($orderId). - Use Case. The synchronous handler calls
$auth->isGranted('order.cancel', $order), andOrderVoterasks the aggregate through$order->isOwnedBy($user->customerId()); the asynchronous variant callsisOwnedBy()directly with theactorIdfrom the command. Petr is the owner → processing continues. If he were not, and the command came through an entry point other than the controller →AccessDeniedDomainException→ HTTP 403. - Aggregate. The handler calls
$order->cancel('changed mind', $now). The aggregate verifies that the order is neither shipped nor delivered and that no more than 24 h have passed since confirmation. Petr confirmed it 30 minutes ago → the state changes toCancelled, and theOrderCancelledevent is created. If it had already shipped →InvalidOrderStateTransitionException→ HTTP 409. - Persistence + outbox. The handler calls
$repo->save($order)and stores the state of the aggregate. With the Outbox Pattern, theOrderCancelledevent goes into the outbox table in the same transaction; the handler above sends it straight to the event bus to keep the example simple. - Field-level (response). The controller redirects to the order detail. If the detail contained
audit_logand Petr were not an admin, the read model would leave it out: for his own order, he sees the status, but not who modified it and when.
Each layer fails in its own way: a different HTTP status, a different error message, different logs. A generic “Access denied” is not enough.
11.07 Field-level – read model filtering#
The previous three layers dealt with actions and the admissibility of an operation. Field-level deals with the visibility of a specific field in an otherwise permitted read. The classic example: both the customer and the admin see the order detail, but only the admin sees the audit_log column (who modified the order and when).
There are two approaches with different trade-offs.
Approach 1: Twig if (view level)
The simplest, but with data leakage: everything is loaded from the database, and part of it is only discarded in the view. For most UIs that is enough; for sensitive data it is not – it leaks through HTML comments, JSON serialization in a JS application, or ETag hashing.
1{# A different variant of the same template than in 11.04. That one reads the aggregate, this one2 reads OrderDetailDto from the read model below – the screen needs the audit log,3 which the aggregate does not carry. Only one of them goes into the project, not both. #}4<dl>5 <dt>Customer</dt> <dd>{{ order.customerId }}</dd>6 <dt>Total</dt> <dd>{{ (order.totalAmount / 100)|number_format(2, ',', ' ') }} CZK</dd>7 <dt>Status</dt> <dd>{{ order.status }}</dd>8 9 {% if is_granted('ROLE_ADMIN') %}10 <dt>Audit log</dt>11 <dd>12 <ul class="audit">13 {% for entry in order.auditLog %}14 <li>{{ entry.at|date }}: {{ entry.action }} ({{ entry.actor }})</li>15 {% endfor %}16 </ul>17 </dd>18 {% endif %}19</dl>
Approach 2: Query filter (read model)
Sensitive fields are never loaded from the database at all, and the read model returns different DTOs depending on the role. Data does not leak; the price is duplication (two queries, two DTO structures). It fits PII, financial data, and audit logs.
1<?php2 3// src/Ordering/Infrastructure/ReadModel/OrderDetailReadModel.php4declare(strict_types=1);5 6namespace App\Ordering\Infrastructure\ReadModel;7 8use App\Ordering\Application\ReadModel\OrderDetailDto;9use App\Ordering\Domain\Exception\OrderNotFoundException;10use App\Ordering\Domain\ValueObject\OrderId;11use Doctrine\DBAL\Connection;12use Symfony\Component\Security\Core\Authorization\UserAuthorizationCheckerInterface;13use Symfony\Component\Security\Core\User\UserInterface;14 15final readonly class OrderDetailReadModel16{17 public function __construct(18 private Connection $db,19 private UserAuthorizationCheckerInterface $auth,20 ) {}21 22 public function forUser(string $orderId, UserInterface $user): OrderDetailDto23 {24 // The read model reads the order_dashboard projection from the CQRS chapter, not25 // the aggregate's table. The total amount is precomputed there; over `orders`26 // it would have to be computed with a join across the items.27 $columns = 'order_id, customer_id, total_amount, status, placed_at';28 $seesAudit = $this->auth->isGrantedForUser($user, 'ROLE_ADMIN');29 30 $sql = "SELECT {$columns} FROM order_dashboard WHERE order_id = :id";31 32 $row = $this->db->fetchAssociative($sql, ['id' => $orderId]);33 if ($row === false) {34 throw OrderNotFoundException::withId(OrderId::fromString($orderId));35 }36 37 // The audit log is a table of its own, not a column of the projection – the query38 // for it is not issued at all when the actor may not see it.39 $row['audit_log'] = $seesAudit40 ? $this->db->fetchAllAssociative(41 'SELECT at, action, actor FROM order_audit_log42 WHERE order_id = :id ORDER BY at',43 ['id' => $orderId],44 )45 : null;46 47 return OrderDetailDto::fromRow($row, includeAudit: $seesAudit);48 }49}
The table is created by a migration. It belongs in the schema_filter from the CQRS chapter
for the same reason as the other projections; otherwise migrations:diff proposes dropping it:
1CREATE TABLE order_audit_log (2 id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,3 order_id UUID NOT NULL,4 at TIMESTAMP(0) NOT NULL,5 action VARCHAR(64) NOT NULL,6 actor VARCHAR(255) NOT NULL7);8 9CREATE INDEX idx_audit_order ON order_audit_log (order_id, at);
# config/packages/doctrine.yaml – the list has to be extended
schema_filter: '~^(?!order_dashboard|reporting_orders|order_audit_log)~'
The read model goes directly to DBAL, so it lives in the infrastructure, the same as the read models in the CQRS chapter.
The DTO it returns belongs to the application layer. It holds only what the screen actually received. auditLog is null if the query
did not select it. Compared with an empty array, this carries a different meaning: the log was not loaded, not that it
contained no entries.
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Application\ReadModel;6 7final readonly class OrderDetailDto8{9 /** @param list<array<string, mixed>>|null $auditLog */10 public function __construct(11 public string $orderId,12 public string $customerId,13 public int $totalAmount,14 public string $status,15 public \DateTimeImmutable $placedAt,16 public ?array $auditLog = null,17 ) {}18 19 /** @param array<string, mixed> $row */20 public static function fromRow(array $row, bool $includeAudit): self21 {22 return new self(23 orderId: (string) $row['order_id'],24 customerId: (string) $row['customer_id'],25 totalAmount: (int) $row['total_amount'],26 status: (string) $row['status'],27 placedAt: new \DateTimeImmutable((string) $row['placed_at']),28 auditLog: $includeAudit ? (array) ($row['audit_log'] ?? []) : null,29 );30 }31}
Choosing between the approaches:
| Criterion | Twig if | Query filter |
|---|---|---|
| Data leakage | Risk (data in memory; with an API/SPA, it leaks into the response) | No |
| Implementation complexity | Trivial | Requires different DTOs / read models |
| Suitable for | hiding in the UI, non-strict protection | PII, finance, audit log, GDPR |
| Testing | Twig integration test | Unit + integration test of the read model |
| Compliance with OWASP A01:2021 | Insufficient – see [8] | Yes (enforcement on the server) |
For non-sensitive data, Twig if is enough and saves time; for sensitive data, always a query filter. The rating in the last row is an interpretation, not a quotation. In the “A01 Broken Access Control” category, OWASP accepts only checks in trusted server-side code and lists among the weaknesses bypassing a check by modifying the HTML page or the API request. Twig if does run on the server, but it has already loaded the data. Anyone who gets to it by another route (API, export) bypasses the condition in the template.
Lists: a Voter cannot answer “which objects may they see?”
A Voter answers a closed question: may this user access this specific object? A list endpoint, however, needs the opposite question: which of ten thousand objects may they see? The difference looks formal; in practice, it is the ceiling of the whole framework built on Voters.
The naive solution loads a page of results and filters it in PHP:
1{# templates/order/list.html.twig (anti-pattern) #}2{% for order in orders %}3 {% if is_granted('order.view', order) %}4 <tr><td>{{ order.id.value }}</td><td>{{ order.status.value }}</td></tr>5 {% endif %}6{% endfor %}
Two things break at once. Pagination stops adding up: the query returns 20 rows, the filter discards 7 of them, and the user sees a page of thirteen items. Nobody counts the total until everything is loaded. Performance also degrades linearly: every row goes through a decision across all registered Voters, so twenty rows and five Voters mean a hundred decisions per render. Without overriding supportsAttribute() and supportsType() (see the implementation details of the Voter), nothing comes off that number.
Authorization therefore belongs in the query. The read model receives the actor's identity and projects it into the WHERE:
1<?php2 3// src/Ordering/Infrastructure/ReadModel/OrderListReadModel.php4declare(strict_types=1);5 6namespace App\Ordering\Infrastructure\ReadModel;7 8use App\Ordering\Domain\ValueObject\CustomerId;9use Doctrine\DBAL\Connection;10 11final readonly class OrderListReadModel12{13 public function __construct(private Connection $db) {}14 15 /** @return list<array<string, mixed>> */16 public function visibleTo(CustomerId $actor, bool $isAdmin, int $limit, int $offset): array17 {18 $sql = 'SELECT order_id, status, total_amount, placed_at FROM order_dashboard';19 $params = ['limit' => $limit, 'offset' => $offset];20 21 // Authorization is part of the query, not of postprocessing22 if (!$isAdmin) {23 $sql .= ' WHERE customer_id = :actor';24 $params['actor'] = $actor->value;25 }26 27 $sql .= ' ORDER BY placed_at DESC LIMIT :limit OFFSET :offset';28 29 return $this->db->fetchAllAssociative($sql, $params);30 }31}
The condition in the WHERE, however, is a second rendering of a rule that OrderVoter already knows. A single definition cannot be kept here, because SQL and PHP are different languages; the link can be named, though. What works is keeping both in one class, or at least in one directory, and adding a comment that refers to the Voter. The main safeguard is a test: it walks through the orders returned by the read model and verifies for each one that the Voter says yes. When the two drift apart, the test fails.
The models that grew up around Zanzibar name this split directly: Check is a question about one object, ListObjects returns a set. For the second of these, Symfony 8 has no native support. A Voter is a good Policy Enforcement Point and claims nothing more. Details in the ReBAC: when a permission is a relationship, not an attribute section.
11.08 Policy-based approach (ABAC)#
RBAC (Role-Based Access Control) asks about the role. ABAC (Attribute-Based Access Control) evaluates a combination of attributes of the subject, the action, the resource, and the context against a policy and returns permit / deny. The move from the first to the second is not decided by the number of rules, but by three qualitative signals: the policy must be readable by someone outside the development team, it changes at a different pace than the code, or several applications share it. As long as none of them applies, Voters are enough, and another abstraction is only extra work.
NIST SP 800-162 provides a vocabulary for this layer that external engines use as well [2]. The PEP (Policy Enforcement Point) is the place where a decision is enforced: in Symfony, access_control, #[IsGranted], and the isGranted() call in the handler. The decision itself is made in the PDP (Policy Decision Point), here the decision manager with its Voters, or possibly a remote engine. The PIP (Policy Information Point) supplies attributes, and the PAP (Policy Administration Point) manages policies. The four-layer framework from 11.02 is therefore a placement of PEPs; the PDP stays single.
The following example builds the ABAC model explicitly: a Policy as a collection of Rule objects evaluated against a subject/user/context triple. Its purpose is to make the model visible. Whether such code is worth writing is discussed at the end of the section; in most Symfony projects, it is not.
1<?php2 3// src/SharedKernel/Authorization/Policy.php4declare(strict_types=1);5 6namespace App\SharedKernel\Authorization;7 8// Three classes, three files – otherwise PSR-4 finds only the first one.9interface Policy10{11 public function name(): string;12 13 /** @return list<Rule> */14 public function rules(): array;15}16 17final readonly class Rule18{19 public function __construct(20 public string $expression,21 public string $description,22 ) {}23}24 25final readonly class PolicyContext26{27 public function __construct(28 public object $subject,29 public object $user,30 public \DateTimeImmutable $now,31 ) {}32}
1<?php2 3// src/Ordering/Authorization/CancelOrderPolicy.php4declare(strict_types=1);5 6namespace App\Ordering\Authorization;7 8use App\SharedKernel\Authorization\Policy;9use App\SharedKernel\Authorization\Rule;10 11final class CancelOrderPolicy implements Policy12{13 public function name(): string14 {15 return 'order.cancel';16 }17 18 /** @return list<Rule> */19 public function rules(): array20 {21 return [22 new Rule(23 // user.customerId is private – ExpressionLanguage does not find24 // a getter for it, so the method is called.25 expression: 'subject.customerId == user.customerId()',26 description: 'Order owner only',27 ),28 new Rule(29 expression: 'subject.status.value == "confirmed"',30 description: 'The order must be confirmed',31 ),32 new Rule(33 expression: 'subject.placedAt.getTimestamp() >= now - 86400',34 description: 'The 24 h cancellation window has not expired yet',35 ),36 ];37 }38}
Writing expressions has its pitfalls, and the errors show only at runtime. ExpressionLanguage reads public properties and calls public methods. It does not find getters for private fields, so the policy subject must have its state readable from outside: either a snapshot with public fields, or an aggregate with public private(set) like the canonical Order. The component cannot subtract a DateTimeImmutable from a number: the date is converted to a Unix timestamp through a method of the object (subject.placedAt.getTimestamp()), and now comes from the evaluator's variables as a number, not as an object. A backed enum is not compared directly: subject.status == "confirmed" fails; what gets compared is the value subject.status.value. And because expressions are strings, static analysis does not see them; every rule must be covered by a test, see Policy: a table-driven unit test.
The rules subject.status.value == "confirmed" and the 24 h window are in the policy only to illustrate the ABAC notation. As section 11.06 describes, domain invariants belong in the aggregate, and the policy checks them at most as a preliminary check (defense in depth). The source of truth remains the aggregate, which rejects an invalid command even without the authorization layer.
A simple PolicyEvaluator evaluates the rules in a given context using Symfony ExpressionLanguage. The package is not in the base installation, so the first step is composer require symfony/expression-language:
1<?php2 3// src/SharedKernel/Authorization/PolicyEvaluator.php4declare(strict_types=1);5 6namespace App\SharedKernel\Authorization;7 8use Symfony\Component\ExpressionLanguage\ExpressionLanguage;9 10final class PolicyEvaluator11{12 public function __construct(private readonly ExpressionLanguage $expr = new ExpressionLanguage()) {}13 14 /**15 * Returns the first violated rule, or null if all of them passed.16 */17 public function evaluate(Policy $policy, PolicyContext $ctx): ?Rule18 {19 $vars = [20 'subject' => $ctx->subject,21 'user' => $ctx->user,22 'now' => $ctx->now->getTimestamp(),23 ];24 foreach ($policy->rules() as $rule) {25 if (!$this->expr->evaluate($rule->expression, $vars)) {26 return $rule;27 }28 }29 return null;30 }31}
What this approach brings and what it costs:
| Policy over ExpressionLanguage | Voter | |
|---|---|---|
| Reason for denial | returns the violated rule | Vote::addReason() since Symfony 7.3 |
| Versioning | a class in the repo, git history | the same |
| Static analysis | expressions are strings, PHPStan does not see them | full |
| Subject | must have publicly readable state | any object |
| Composition of votes | custom code | AccessDecisionManager and strategies |
The last two rows are the hidden cost that tables of benefits usually leave out. ExpressionLanguage sees only public properties and methods. The canonical Order with public private(set) meets that; an aggregate whose state is readable only through private fields does not. Then an extra snapshot appears, which has to be kept in sync with the domain. On top of that, votes are composed by a custom evaluator instead of the decision manager, so the strategies from 11.04 do not apply.
Custom evaluator, or a Voter with Vote?
There used to be one strong argument for a custom PolicyEvaluator: knowing which rule failed, not just that access was not granted. Since Symfony 7.3, the Security component can do this by itself. A Voter accepts the optional parameter ?Vote $vote and can write a reason into it. The application layer then reads the whole decision through Security::getAccessDecision(), which was added in version 7.4:
1// src/Ordering/Infrastructure/Security/OrderVoter.php (with reasons, only the CANCEL branch)2protected function voteOnAttribute(3 string $attribute,4 mixed $subject,5 TokenInterface $token,6 ?Vote $vote = null,7): bool {8 $user = $token->getUser();9 if (!$user instanceof SecurityUser) {10 $vote?->addReason('The actor is not a logged-in application user.');11 return false;12 }13 14 if (!$subject->isOwnedBy($user->customerId())) {15 $vote?->addReason('Only the owner may cancel the order.');16 return false;17 }18 19 if (!$subject->isCancellable(new \DateTimeImmutable())) {20 $vote?->addReason('The 24 h window for cancelling the order has expired.');21 return false;22 }23 24 return true;25}
The reasons are read from the public property $vote->reasons (an array of strings); the Vote class has no getter. The same goes for AccessDecision, where the result is the $decision->isGranted property. The application layer pulls them out of the AccessDecision and passes them into the error response:
1// src/Ordering/Infrastructure/Http/ExplainedAccessDenied.php2$decision = $this->security->getAccessDecision(OrderVoter::CANCEL, $order);3 4if (!$decision->isGranted) {5 $reasons = [];6 foreach ($decision->votes as $vote) {7 // Vote::$reasons is a public property, not a getter8 $reasons = array_merge($reasons, $vote->reasons);9 }10 11 throw new AccessDeniedDomainException(implode(' ', $reasons));12}
The example deliberately checks the state of the aggregate as well, to show what is gained. The rule, however, stays defined in Order::isCancellable(); the Voter calls it rather than copying it.
The conclusion for Symfony 8: a custom Policy/Rule layer does not pay off. It gives the same answers as Voters, but without static analysis, without decision strategies, and with an extra model. ABAC remains useful as a way of thinking about rules, but the implementation is built from Voters. An external engine comes into play only when the policy has to live outside the application: several services share it, another team manages it, or an auditor checks it independently of the deploy cycle. That is when OPA with the Rego language or Cerbos becomes an option, and the Voter turns into a thin PEP that asks a remote PDP. The interface between them is standardized by the AuthZEN Authorization API 1.0, approved in January 2026 [9].
ReBAC: when a permission is a relationship, not an attribute
OPA is not the last stop. The shift of recent years points toward ReBAC (Relationship-Based Access Control), where access is derived from relationships between users and objects and between objects themselves. A typical rule: “a user sees a document if they have access to its parent folder.” RBAC fails on hierarchies, sharing, and multi-tenancy: either a role appears for every combination, or the logic fragments across Voters.
The reference model is Zanzibar, Google's authorization system described at USENIX ATC '19. It stores relationships as object#relation@user tuples, describes the relationship configuration in its own namespace language, and handles consistency with tokens called zookies. The operational numbers from the paper give a sense of scale: trillions of ACL entries, millions of authorization checks per second, and p95 latency under 10 ms. Today there are two open implementations of the same model: OpenFGA (a CNCF project) and SpiceDB from Authzed, with a schema language that distinguishes stored relationships from computed permissions.
11.09 Multi-tenancy – tenant context#
Multi-tenancy is a special case of ABAC: one application serves several separate customers (organizations, clients, tenants), and none of them may see another's data. There are three architectural strategies:
- Row-based – a shared database, shared tables, a
tenant_idcolumn everywhere. The cheapest, the least isolation, and it requires careful filters. - Schema-based – a shared database, a separate schema per tenant (PostgreSQL
SET search_path). Medium isolation. Performance depends on the number of tenants: smaller tables help large tenants, but thousands of schemas burden the catalog, migrations, and connection pooling. - Database-based – a separate database per tenant. The highest isolation and the highest cost (a DB connection per tenant, migrations × N).
The choice among them relates to the size of the installation. Row-based suits a SaaS with a large number of small tenants, schema-based fits where backups and migrations should be separated per tenant, and database-based is for regulated domains. The criterion is the same every time: how expensive the mistake is when two tenants meet in one response. For row-based, the established tool in Symfony is the Doctrine SQLFilter.
This looks like a contradiction of mistake 3, which labeled filtering in the persistence layer an anti-pattern. The contradiction is only apparent, and the difference lies in what the filter answers. The tenant is the context of the query, not an authorization decision about an action: a dimension that every query in a request carries, just like the language or the time zone. The decision “Petr may cancel order #42” does not belong in SQL, because the handler then cannot tell a nonexistent record from a foreign one. The question “which tenant does this request belong to” does belong in SQL, because the answer is single and unchanging for the whole request.
1<?php2 3// src/SharedKernel/Infrastructure/Doctrine/TenantFilter.php4declare(strict_types=1);5 6namespace App\SharedKernel\Infrastructure\Doctrine;7 8use App\SharedKernel\Domain\TenantAware;9use Doctrine\ORM\Mapping\ClassMetadata;10use Doctrine\ORM\Query\Filter\SQLFilter;11 12final class TenantFilter extends SQLFilter13{14 public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias): string15 {16 if (!$targetEntity->reflClass->implementsInterface(TenantAware::class)) {17 return '';18 }19 20 return sprintf(21 '%s.tenant_id = %s',22 $targetTableAlias,23 $this->getParameter('tenant_id'),24 );25 }26}
The marker interface is empty and says only “this entity belongs to a tenant.” Without it, the filter
fails on the first query with Interface … does not exist, and because it is enabled globally,
it brings down every query in the application:
1<?php2 3declare(strict_types=1);4 5namespace App\SharedKernel\Domain;6 7/**8 * A marker for entities that belong to a specific tenant. It has no methods –9 * the filter only asks whether the entity implements it.10 */11interface TenantAware12{13}
The filter adds a tenant_id = ? clause to every query on an entity that implements TenantAware. As long as no entity implements it, the filter is a no-op: enabled, but without effect. The marker does not belong on SecurityUser. That class is loaded by the provider inside the firewall, that is, before the listener manages to set the parameter, and login would fail with Parameter 'tenant_id' does not exist. The tenant-scoped classes are the domain entities behind the firewall, not the class the firewall uses for authentication. Enabling the filter in config/packages/doctrine.yaml:
1# config/packages/doctrine.yaml2doctrine:3 orm:4 filters:5 tenant:6 class: App\SharedKernel\Infrastructure\Doctrine\TenantFilter7 enabled: true # fail-closed: the filter always runs, the listener supplies the parameter
Watch the default state. A disabled or unconfigured filter adds no WHERE to the SQL, and the query returns the data of all tenants. The SQLFilter is fail-open by its nature, and that is the main risk of the whole approach. The configuration above therefore enables the filter globally (enabled: true): it runs for every query, and a missing tenant_id ends in an exception, not in a data leak.
One gap remains even then. The filter does not cover loading the inverse side of a one-to-one association.
Measured on ORM 3.6, the other end of the relationship returns even a record of a foreign tenant, although through find()
or DQL you would not get the same record. Where security depends on tenant separation, the tenant check
also belongs in the domain layer, not only in the filter.
The parameter value is supplied by a kernel event listener after authentication:
1<?php2 3// src/SharedKernel/Infrastructure/Http/TenantContextListener.php4declare(strict_types=1);5 6namespace App\SharedKernel\Infrastructure\Http;7 8use Doctrine\ORM\EntityManagerInterface;9use Symfony\Component\EventDispatcher\Attribute\AsEventListener;10use Symfony\Component\HttpKernel\Event\RequestEvent;11use Symfony\Component\HttpKernel\KernelEvents;12use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;13 14#[AsEventListener(event: KernelEvents::REQUEST, priority: 7)]15final readonly class TenantContextListener16{17 public function __construct(18 private EntityManagerInterface $em,19 private TokenStorageInterface $tokens,20 ) {}21 22 public function __invoke(RequestEvent $event): void23 {24 if (!$event->isMainRequest()) {25 return;26 }27 28 $token = $this->tokens->getToken();29 $user = $token?->getUser();30 if ($user === null || !method_exists($user, 'tenantId')) {31 return; // public endpoint, anonymous request32 }33 34 $tenantId = $user->tenantId()->value;35 $filter = $this->em->getFilters()->enable('tenant');36 $filter->setParameter('tenant_id', $tenantId);37 }38}
Calling enable('tenant') in the listener is harmless for a globally enabled filter: it returns the existing instance, on which you only set the parameter.
Three details:
- Priority 7 in
AsEventListener. In Symfony, higher priority = earlier execution. The firewall registers itsonKernelRequestwith priority 8, so a listener that already needs the authenticated user must have a priority lower than 8 (typically 7 or 0). Details in the EventDispatcher documentation. - Main request guard. Without
$event->isMainRequest(), the filter would also be set for sub-requests (ESI, render fragments), where there usually is no token and the listener would fail. - An anonymous request does not get the parameter. For public endpoints (login, register, health), the listener stops at the guard, and
tenant_idstays unset. The first query on aTenantAwareentity then throws an exception, because a globally enabled filter without a parameter does not let the query through. The loud failure is intentional here: a public endpoint has no tenant data to read. If it reads some anyway, the request should be rejected already at the firewall.
PostgreSQL Row-Level Security
For the hole described above, PostgreSQL has a solution one level lower. Row-Level Security moves filtering into the database, so it applies to native SQL, to console scripts, and to connections from outside the application as well:
1-- migrations/tenant_rls.sql2ALTER TABLE orders ENABLE ROW LEVEL SECURITY;3-- Without FORCE, the policy does not apply to the table owner4ALTER TABLE orders FORCE ROW LEVEL SECURITY;5 6CREATE POLICY tenant_isolation ON orders7 USING (tenant_id = current_setting('app.tenant_id', true))8 WITH CHECK (tenant_id = current_setting('app.tenant_id', true));
The application then sets the connection variable with SET app.tenant_id = '…' before its queries, in the same listener that fills the Doctrine filter. RLS differs from the SQLFilter in its default behavior, and that is what decides. After ENABLE ROW LEVEL SECURITY, the table is default-deny: without a policy, nothing is returned. The SQLFilter, by contrast, is fail-open, and fail-closed behavior has to be built by hand, as the previous callout describes. The price of RLS is being tied to PostgreSQL, harder debugging (the query returns nothing, and nowhere does it say why), and a role with the BYPASSRLS attribute, which migrations and backups need. The two layers do not exclude each other: the filter keeps the behavior in the ORM readable, and RLS is the last safety net.
11.10 Testing pyramid for authorization#
Each of the four layers is tested with a different kind of test. Anyone who tries to cover everything end-to-end ends up with a slow and brittle suite. The split follows the classic testing pyramid: many fast unit tests, fewer integration tests, a handful of end-to-end tests.
Aggregate-level: a pure unit test
The domain rules in the aggregate are pure PHP without a framework or a database, so the test is fast and deterministic.
The tests reach for OrderFactory, which keeps the assembly of the aggregate in one place. In the
taxonomy from Testing DDD, it is an Object Mother: named
static methods return ready-made scenarios (placed(), shipped()). It has nothing in common with the Foundry factory
of the same name from that chapter. It pays off as soon as more than one
test file needs it:
1<?php2 3declare(strict_types=1);4 5namespace App\Tests\Ordering\Domain;6 7use App\Ordering\Domain\Model\Order;8use App\Ordering\Domain\ValueObject\CustomerId;9use App\Ordering\Domain\ValueObject\ProductId;10use App\Shipping\Domain\ValueObject\ShipmentId;11use App\SharedKernel\Domain\Currency;12use App\SharedKernel\Domain\Money;13 14final class OrderFactory15{16 private const AT = '2026-04-29 10:00:00';17 18 public static function placed(19 string $at = self::AT,20 ?CustomerId $customerId = null,21 ): Order {22 return self::build($customerId ?? CustomerId::generate(), $at);23 }24 25 public static function placedFor(CustomerId $customerId): Order26 {27 return self::build($customerId, self::AT);28 }29 30 // The owner is a parameter here too. Without it, the policy tests would report31 // an ownership violation instead of the rule they meant to verify.32 public static function shipped(?CustomerId $customerId = null): Order33 {34 $order = self::build($customerId ?? CustomerId::generate(), self::AT);35 $order->markPaid();36 $order->ship(ShipmentId::generate());37 38 return $order;39 }40 41 /**42 * The factory goes through the aggregate's public API, not through reflection. The constructor43 * is private and the state changes only through transitions – if the test reached inside,44 * it would stop guarding exactly the rules it exists for.45 */46 private static function build(CustomerId $customerId, string $at): Order47 {48 // The last parameter is the confirmation time. Without it, the scenario49 // “confirmed at 10:00, cancelled at 12:00” could not be built other50 // than through reflection – and the test would stop guarding the aggregate's rules.51 $order = Order::placeWithFirstItem(52 $customerId,53 ProductId::generate(),54 1,55 new Money(10_000, Currency::CZK),56 new \DateTimeImmutable($at),57 );58 59 $order->releaseEvents(); // the event queue belongs to the test, not to the factory60 61 return $order;62 }63}
1<?php2 3// tests/Ordering/Domain/OrderCancelTest.php4declare(strict_types=1);5 6namespace App\Tests\Ordering\Domain;7 8use App\Ordering\Domain\Event\OrderCancelled;9use App\Ordering\Domain\Exception\CancellationWindowExpiredException;10use App\Ordering\Domain\Exception\InvalidOrderStateTransitionException;11use App\Ordering\Domain\Model\Order;12use PHPUnit\Framework\TestCase;13 14final class OrderCancelTest extends TestCase15{16 public function testCancelWithinWindowSucceeds(): void17 {18 $order = OrderFactory::placed(at: '2026-04-29 10:00:00');19 $order->releaseEvents(); // clears the events from the creation phase20 21 $order->cancel('changed mind', new \DateTimeImmutable('2026-04-29 12:00:00'));22 23 // The state is verified through behavior: a successful cancel records OrderCancelled24 $events = $order->releaseEvents();25 self::assertCount(1, $events);26 self::assertInstanceOf(OrderCancelled::class, $events[0]);27 }28 29 public function testCancelOfShippedOrderThrows(): void30 {31 $order = OrderFactory::shipped();32 33 $this->expectException(InvalidOrderStateTransitionException::class);34 $order->cancel('changed mind', new \DateTimeImmutable());35 }36 37 public function testCancelAfter24hThrows(): void38 {39 $order = OrderFactory::placed(at: '2026-04-29 10:00:00');40 41 $this->expectException(CancellationWindowExpiredException::class);42 $order->cancel('too late', new \DateTimeImmutable('2026-04-30 11:00:00'));43 }44}
Voter: a unit test with a TokenInterface stub
A Voter receives a TokenInterface; in a test, a stub of it is enough, together with a real subject and a stub of the decision manager for roles. The test does not need the Symfony Kernel:
1<?php2 3// tests/Ordering/Infrastructure/Security/OrderVoterTest.php4declare(strict_types=1);5 6namespace App\Tests\Ordering\Infrastructure\Security;7 8use App\Ordering\Domain\ValueObject\CustomerId;9use App\Ordering\Infrastructure\Security\OrderVoter;10use App\Tests\Identity\SecurityUserFixture;11use App\Tests\Ordering\Domain\OrderFactory;12use PHPUnit\Framework\TestCase;13use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;14use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;15use Symfony\Component\Security\Core\Authorization\Voter\Voter;16 17final class OrderVoterTest extends TestCase18{19 // The identifiers are UUIDs – CustomerId accepts no other value.20 private const OWNER = '018f4d2e-7a31-7c9e-b4d0-6f2a1c8e5b03';21 private const STRANGER = '02b5e8c1-9d44-7f10-a8b7-3e5c9d21f746';22 23 public function testOwnerCanCancelOwnOrder(): void24 {25 $order = OrderFactory::placedFor(CustomerId::fromString(self::OWNER));26 27 self::assertSame(28 Voter::ACCESS_GRANTED,29 $this->voteCancel($order, actor: self::OWNER)30 );31 }32 33 public function testStrangerCannotCancelOrder(): void34 {35 $order = OrderFactory::placedFor(CustomerId::fromString(self::OWNER));36 37 self::assertSame(38 Voter::ACCESS_DENIED,39 $this->voteCancel($order, actor: self::STRANGER)40 );41 }42 43 private function voteCancel(object $order, string $actor): int44 {45 // Without expectations, these are stubs, not mocks – createMock() would report46 // “No expectations were configured” on PHPUnit 13 and stop working in 14.47 $decisions = $this->createStub(AccessDecisionManagerInterface::class);48 $decisions->method('decide')->willReturn(false); // the actor has no extra role49 50 $token = $this->createStub(TokenInterface::class);51 $token->method('getUser')->willReturn(SecurityUserFixture::for($actor));52 53 return (new OrderVoter($decisions))->vote($token, $order, [OrderVoter::CANCEL]);54 }55}
1<?php2 3declare(strict_types=1);4 5namespace App\Tests\Identity;6 7use App\Identity\Infrastructure\Security\SecurityUser;8 9final class SecurityUserFixture10{11 /** An actor for the Voter test. Only customerId matters to it, the rest is filler. */12 public static function for(string $customerId, string ...$roles): SecurityUser13 {14 // The email is the primary key, so it must differ for each actor –15 // two fixtures with the same one would collide when saved.16 return new SecurityUser(17 email: $customerId . '@example.test',18 passwordHash: 'irrelevant',19 roles: $roles ?: ['ROLE_USER'],20 customerId: $customerId,21 tenantId: 'tenant-test',22 );23 }24}
The AccessDecisionManagerInterface stub deliberately returns false. The test thus verifies ownership without the influence of roles; for a scenario with an admin, a second test with the return value true is enough.
End-to-end: WebTestCase
The whole pipeline (firewall → controller → handler → Voter → aggregate) is covered by Symfony's WebTestCase. That is already an integration test with the kernel and a database. A reasonable measure: one e2e test per use case, covering the main scenario and one or two of the most important error states. Edge cases belong in unit tests on the lower layers.
Logging in in such a test does not go through the form. KernelBrowser::loginUser() puts the user straight into the session and saves one request as well as a dependency on the shape of the login page. One link remains, however: with the entity provider, the firewall reloads the user on every subsequent request, so the fixture must be in the database. Otherwise the test ends with a redirect to /login and looks like an authorization failure.
1<?php2 3// tests/Ordering/Http/CancelOrderE2eTest.php4declare(strict_types=1);5 6namespace App\Tests\Ordering\Http;7 8use App\Ordering\Domain\Model\Order;9use App\Ordering\Domain\Repository\OrderRepository;10use App\Ordering\Domain\ValueObject\CustomerId;11use App\Tests\Identity\SecurityUserFixture;12use App\Tests\Ordering\Domain\OrderFactory;13use Doctrine\ORM\EntityManagerInterface;14use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;15 16final class CancelOrderE2eTest extends WebTestCase17{18 private const OWNER = '018f4d2e-7a31-7c9e-b4d0-6f2a1c8e5b03';19 private const STRANGER = '02b5e8c1-9d44-7f10-a8b7-3e5c9d21f746';20 21 protected function setUp(): void22 {23 // The fixture is written to the database, so it has to be cleaned up – otherwise24 // the second run fails on a unique index, not on the tested behavior.25 // A more convenient alternative is dama/doctrine-test-bundle, which26 // wraps each test in a transaction and rolls it back at the end.27 $connection = static::getContainer()28 ->get(EntityManagerInterface::class)29 ->getConnection();30 31 foreach (['order_items', 'orders', 'app_user'] as $table) {32 $connection->executeStatement('DELETE FROM ' . $table);33 }34 35 // getContainer() boots the kernel, but createClient() wants to36 // start it again. Without this line, the test fails with37 // “Booting the kernel before calling createClient() is not supported”.38 self::ensureKernelShutdown();39 }40 41 public function testStrangerGetsNotFound(): void42 {43 $client = static::createClient();44 $order = $this->givenOrderOf(self::OWNER);45 46 // loginUser() puts the user into the session, but on the next request47 // the firewall refreshes it through the entity provider – so the user must48 // be in the database, otherwise the token is discarded and the test ends on /login.49 $stranger = SecurityUserFixture::for(self::STRANGER);50 $container = static::getContainer();51 $container->get(EntityManagerInterface::class)->persist($stranger);52 $container->get(EntityManagerInterface::class)->flush();53 54 $client->loginUser($stranger);55 $client->request('POST', '/order/' . $order->id->value . '/cancel');56 57 // #[IsGranted(..., statusCode: 404)] prevents enumeration of foreign IDs58 self::assertResponseStatusCodeSame(404);59 }60 61 private function givenOrderOf(string $customerId): Order62 {63 $container = static::getContainer();64 $order = OrderFactory::placedFor(CustomerId::fromString($customerId));65 66 $container->get(OrderRepository::class)->save($order);67 $container->get(EntityManagerInterface::class)->flush();68 69 return $order;70 }71}
Architecture test: a domain without the Security component
Anti-pattern 4 forbids a dependency of the domain on Symfony\Component\Security. A rule guarded only by code review gets broken sooner or later, so a test enforces it. With PHPArkitect, one rule is enough:
1// tests/Architecture/DomainRules.php2Rule::allClasses()3 ->that(new ResideInOneOfTheseNamespaces('App\*\Domain\*'))4 ->should(new NotDependsOnTheseNamespaces('Symfony\Component\Security'))5 ->because('the domain model must not know the authorization infrastructure');
The test runs in CI next to the unit tests and fails on the first forbidden import, not during a refactoring a year later. The pyramid, fixture builders, and other architecture rules are covered in the chapter on testing.
Policy: a table-driven unit test
In the policy-based approach, each rule is one test case. Evaluating the expressions relies on the symfony/expression-language package, which is not in the base installation. A table-driven test with a data provider serves best: one row = one scenario, readable even for a non-technical reviewer:
1<?php2 3// tests/Ordering/Authorization/CancelOrderPolicyTest.php4declare(strict_types=1);5 6namespace App\Tests\Ordering\Authorization;7 8use App\Ordering\Authorization\CancelOrderPolicy;9use App\Ordering\Domain\ValueObject\CustomerId;10use App\SharedKernel\Authorization\PolicyContext;11use App\SharedKernel\Authorization\PolicyEvaluator;12use App\Tests\Identity\SecurityUserFixture;13use App\Tests\Ordering\Domain\OrderFactory;14use PHPUnit\Framework\Attributes\DataProvider;15use PHPUnit\Framework\TestCase;16 17final class CancelOrderPolicyTest extends TestCase18{19 private const OWNER = '018f4d2e-7a31-7c9e-b4d0-6f2a1c8e5b03';20 private const STRANGER = '02b5e8c1-9d44-7f10-a8b7-3e5c9d21f746';21 22 public static function scenarios(): iterable23 {24 yield 'happy path' => [25 'subject' => OrderFactory::placedFor(CustomerId::fromString(self::OWNER)),26 'user' => SecurityUserFixture::for(self::OWNER),27 'expected' => null,28 ];29 yield 'wrong customer' => [30 'subject' => OrderFactory::placedFor(CustomerId::fromString(self::OWNER)),31 'user' => SecurityUserFixture::for(self::STRANGER),32 'expected' => 'Order owner only',33 ];34 yield 'shipped order' => [35 'subject' => OrderFactory::shipped(CustomerId::fromString(self::OWNER)),36 'user' => SecurityUserFixture::for(self::OWNER),37 'expected' => 'The order must be confirmed',38 ];39 yield 'window expired' => [40 'subject' => OrderFactory::placed('2026-04-28 09:00:00', CustomerId::fromString(self::OWNER)),41 'user' => SecurityUserFixture::for(self::OWNER),42 'expected' => 'The 24 h cancellation window has not expired yet',43 ];44 }45 46 #[DataProvider('scenarios')]47 public function testEvaluate(object $subject, object $user, ?string $expected): void48 {49 $evaluator = new PolicyEvaluator();50 // The evaluation time is fixed; otherwise the window scenario would51 // start failing on its own a year later.52 $context = new PolicyContext($subject, $user, new \DateTimeImmutable('2026-04-29 12:00:00'));53 54 $violation = $evaluator->evaluate(new CancelOrderPolicy(), $context);55 56 self::assertSame($expected, $violation?->description);57 }58}
Compared with a test that has a method per case, the table has two advantages. A new rule means one extra row in scenarios(). And the whole test serves as executable documentation of the policy: a reviewer outside the development team sees all cases in one table and can approve the domain rules.
11.11 Anti-patterns#
The four anti-patterns roughly follow the structure “symptom – consequence – remedy.” The first two summarize what the chapter has already covered, so that the whole list can be walked through in one place during code review.
Anti-pattern 1: authorization in the controller
Covered in section 11.01. Symptom: the same authorization condition repeated in three or more controllers and missing from the versions called from a console command or a Messenger handler. Remedy: move it into a Voter and call AuthorizationCheckerInterface in the Application Service. Related: general anti-patterns in DDD.
Anti-pattern 2: a Voter that loads its own subject
Covered in the A Voter does not load the subject it decides about callout. Symptom: the Voter's constructor accepts a repository, and voteOnAttribute() calls find($subject) on an ID it received instead of the object. Consequence: a second query for the same entity and a decision on a state that may have changed in the meantime. Remedy: the handler loads the entity once and passes it to isGranted(). The Voter may load supplementary data outside the subject (membership, delegation); the ban targets the subject, not all queries.
Anti-pattern 3: Voter == aggregate logic
Symptom: the cancellation window (“the order not older than 24 h”) is written both in the Voter and in Order::cancel(). When the rule changes (the window is extended to 48 h), both places have to be updated, and one of them typically gets forgotten.
Remedy: the rule belongs in the aggregate, because it is a domain invariant. The Voter does not verify the domain state of the aggregate; it answers only about the user's identity and roles and about ownership of the subject. To hide a button in the view, Twig combines {% if is_granted(...) and order.isCancellable(now) %}: the Voter for the permission, the domain method for the state.
Anti-pattern 4: the Symfony User pulled into the domain aggregate
Symptom:
1<?php2 3// src/Ordering/Domain/Model/Order.php (anti-pattern)4namespace App\Ordering\Domain\Model;5 6use Symfony\Component\Security\Core\User\UserInterface;7 8final class Order9{10 // Anti-pattern: the domain depends on the Symfony Security component11 public function cancel(UserInterface $user, string $reason): void12 {13 if ($user->getUserIdentifier() !== $this->customerEmail) {14 throw new \DomainException('Not your order');15 }16 // ...17 }18}
The technical consequence: the domain depends on Symfony\Component\Security, so the same code cannot run from a console command, from a Messenger worker, or from a unit test without the Kernel. The modeling consequence weighs more. Roles and permissions are the vocabulary of another subdomain, the Identity & Access context from 11.02. As soon as they appear in Order::cancel(), the Ordering context speaks a foreign Ubiquitous Language, and the boundary between the contexts blurs.
Remedy: the domain works with its own type (CustomerId, TenantId), the application handler translates SecurityUser into the domain identifier, and the architecture test enforces it. The opposite direction of the same layering violation, that is, domain logic in the infrastructure, is covered in the chapter on anti-patterns.
11.12 Summary#
Authorization in a DDD application on Symfony 8 sits on four layers, each with its own Symfony tool and its own granularity:
- Edge – Symfony firewall +
access_control. Anonymous vs. logged in, a coarse split by roles. No domain knowledge. - Use Case – Symfony Voter. “May Petr cancel order #42?” The application handler checks the permission before the domain operation: synchronously through
isGranted(), in the worker against theactorIdfrom the command. The domain does not know the Security component. - Aggregate – a domain invariant + a domain exception. “An order cannot be cancelled after it has shipped or later than 24 h after confirmation.” The aggregate throws
InvalidOrderStateTransitionExceptionorCancellationWindowExpiredException; the HTTP layer maps them to 409 Conflict. - Field – Twig
is_grantedin the view (with the risk of data leakage), or a query filter / read model for sensitive data (PII, audit log). Lists need a filter in the query, not a Voter over every row.
RBAC covers coarse permissions. As soon as the rules depend on relationships between entities, thinking in ABAC terms takes over, implemented, however, from Voters, not from a custom policy layer. Multi-tenancy is handled by a Doctrine SQLFilter with a kernel listener, set up fail-closed, and in PostgreSQL also by RLS as a safety net beneath the application. A domain state rule belongs in the aggregate; the actor's relationship to the aggregate (ownership) is also defined by the aggregate, and the Voter asks it.
When to leave Voters is not determined by the number of rules, but by three questions: must the policy be readable outside the development team, does it change at a different pace than the code, do several applications share it? As long as the answer is no three times, Voters with Vote::addReason() are the cheaper option. At the first yes, an external engine (OPA, Cerbos) comes in, and the Voter becomes a thin enforcement point.
Practical checklist before deploy
Before you commit an authorization change, go through these nine points:
- Is there a default-deny rule at the end of
access_control? If not: a new endpoint without an explicit role is public. - Does the Application Handler check the permission (
isGranted(), in the worker theactorIdfrom the command) before the domain operation? If not: authorization can be bypassed through an alternative entry point (CLI, Messenger). - Is the domain invariant written in the aggregate, not in the Voter? If not: the rule is bypassed by calling the aggregate method directly outside the handler.
- Is the decision strategy set to
unanimous? If not: with the defaultaffirmative, one approving Voter overrides all the disagreeing ones. - Does the application return 403, 404, or 409 depending on the type of failure? If not: the user gets a confusing message, or foreign identifiers can be enumerated.
- Do sensitive fields (PII, audit) have a query filter, not just a Twig if? If not: data leaks through the JSON API, dev tools, or the ETag.
- Does the list endpoint filter in the query, not through
is_granted()over every row? If not: pagination falls apart and performance degrades linearly. - If the application is multi-tenant: does the Doctrine SQLFilter have a fail-closed default? If not: a missing tenant context returns all data.
- Is there at least one test on every layer, including the architecture test? An aggregate test, a Voter test, an e2e test, and a ban on importing Security in the domain.
Frequently asked questions
Should I write one Voter per entity, or more?
One Voter per entity that covers N attributes (VIEW, CANCEL, REFUND, …). In supports(), it filters by $subject instanceof Order and by a whitelist of attributes; in voteOnAttribute(), the attributes are mapped through a match expression to private methods. Several Voters per entity pay off only when the permissions need completely different dependencies (typically ownership vs. roles) and you want to test them independently. Details in the Use Case – Symfony Voter section.
May a Voter load an aggregate from the database?
Not the subject it decides about. The Voter receives it as $subject; the handler has already loaded it and passes it in memory. A second load is an anti-pattern (11.11): it leads to a duplicate query and to deciding on a state that may have changed in the meantime. The Voter does have to load supplementary data that is not on the subject (team membership, delegation, a tenant hierarchy), and Symfony assumes injected services in a Voter. Such queries belong behind a cache valid for the duration of the request.
When is ROLE_USER enough, and when is an attribute-based approach needed?
RBAC (roles) is enough as long as “the role describes the permission by itself” holds: ROLE_ADMIN may do everything, ROLE_REFUND_AGENT may issue refunds regardless of the specific entity. As soon as permissions depend on relationships (ownership, tenant, a time window, the state of the aggregate), RBAC grows out of hand and narrowly specific roles such as ROLE_TENANT_42_ORDER_AGENT appear. That is when thinking in ABAC terms takes over (11.08): the decision evaluates attributes of the subject, the user, and the context. It does not mean writing a custom policy engine; in Symfony 8, the same thing is built from Voters, which can also return the reason for a denial.
What if we have 100 different roles?
That is usually a symptom that the roles replicate data that belongs in entities. Instead of ROLE_TENANT_42_ADMIN, ROLE_TENANT_43_ADMIN, …, an attribute user.tenantId, one generic role ROLE_TENANT_ADMIN, and a Voter that verifies user.tenantId == subject.tenantId are enough. This simplifies user management, audit, and delegation. Details in the Multi-tenancy – tenant context section.
May a domain aggregate depend on the Symfony Security component?
No. The domain must be independent of the framework. Otherwise it cannot be unit-tested without the Kernel, shared between the web and the CLI, or moved to another framework. The modeling reason, however, is stronger than the technical one: roles and permissions are the vocabulary of the Identity & Access context, not of the context in which the aggregate lives. If the aggregate needs to “know” the user, it gets its own domain type (CustomerId). The application handler takes care of the translation from SecurityUser. Details in anti-pattern 4 in 11.11.
Where should the audit log of authorization decisions be stored?
Three options, depending on compliance requirements: (1) Symfony Monolog with a custom authorization channel, which is enough for most applications, logging to a file / ELK / Loki; (2) a domain table authorization_decisions with parameters (user_id, attribute, subject_id, decision, policy_version), suitable for regulated domains (PCI DSS, healthcare); (3) an external audit service (AWS CloudTrail, Datadog) for multi-tenant SaaS. The simplest is a decorator over AuthorizationCheckerInterface that logs every call; the votes of individual voters, however, are visible only to a custom AccessDecisionStrategyInterface or to Security::getAccessDecision(). Details in the Audit log of authorization decisions section.
11.13 Further reading#
- Symfony Security component – official documentation
- Symfony Voters – Custom Authorization
- OWASP Top 10 (2021): A01 – Broken Access Control
- NIST SP 800-162 – Guide to Attribute-Based Access Control
- OpenID Connect Core 1.0 – an authentication layer on top of OAuth 2.0
- Stripe API keys – restricted keys with an explicit scope
- Symfony – how access_control works
- Open Policy Agent (OPA) – an external policy engine
- OpenFGA – Authorization Concepts (ReBAC, the Zanzibar model)
- PostgreSQL – Row Security Policies
- Noback, M.: Decoupling your security user from your user model (2022)
- Pang, R. et al.: Zanzibar: Google's Consistent, Global Authorization System. USENIX ATC '19, Renton, WA, 2019.
- Vernon, V.: Implementing Domain-Driven Design. Addison-Wesley, 2013. Chapter 14, “Application,” and the Identity and Access Context.