The problem
Take the order service of an online shop,
exposed with API Platform. A customer only reads their own
orders; the support team reads them all. The
internalNote field, where the support team
records its exchanges, must never reach the customer.
On the REST side, a Doctrine extension adds
customer = :user to every query of a customer,
and internalNote carries a property security
rule:
// src/Entity/Order.php (excerpt)
#[ORM\Entity]
#[ORM\Table(name: 'orders')]
#[ApiResource(mercure: true)] // the shortest configuration
class Order
{
#[ORM\ManyToOne]
#[ORM\JoinColumn(nullable: false)]
private Customer $customer;
#[ORM\Column(type: Types::TEXT, nullable: true)]
#[ApiProperty(security: "is_granted('ROLE_SUPPORT')")]
private ?string $internalNote = null;
// ...
}
A customer asking for someone else's order gets a 404, and
their own orders come without internalNote.
With mercure: true, an API Platform Doctrine
listener serializes the entity after each
flush() and publishes it to the hub. This path
goes neither through the Doctrine provider nor through the
extension.
Three leaks follow.
The update is public by default. The
private option is false when it is
not set. The hub then delivers the order to every subscriber
whose subscription covers its topic, whatever their token.
"Private" does not mean "for the owner only".
A private update goes to every token that grants one of its
topics. If the token of every signed-in customer grants
https://example.com/orders/*, every customer
receives everybody else's orders.
The content depends on the author, not on the
reader.
The listener serializes once, in the request that changed
the order. The internalNote rule is therefore
evaluated with the rights of the support agent. The note
goes out with the update, to its whole audience.
A draft, a cancellation reason or a moderation remark leaks the same way.
The options
Keep mercure: true, in private mode
- What it solves: one option is enough, and the hub no longer delivers anything to tokens that cover none of the topics.
- What it costs: the content is still computed with the author's rights, and the topics and tokens still have to be written.
Per-customer topics and the full content
- What it solves: each customer only receives their own orders, through an alternate topic in their own space.
- What it costs: the same content for every audience. Each internal field has to be removed by hand, including those added later.
One publication per audience
- What it solves: each audience receives its own view, serialized with its own groups, on a topic reserved for it.
- What it costs: two serializations and two topics for each change, and the permission rule copied into the publishing code.
A signal, then a REST read
-
What it solves: the update only carries
the order's IRI. The front reads it again with a
GET, which goes through the extension and the property security. - What it costs: one more request per event and per subscriber, and a display that lags by one round trip.
Our recommendation
Rights of its own for the real-time channel: a private signal, one topic per audience, a token limited to what the user reads.
Both paths lead to the same browser, but only the REST path goes through the extension. We do not rebuild the extension inside the hub: we limit what the hub carries.
The topic carries the audience
The canonical topic
https://example.com/orders/{id} serves the
support team. The alternate topic
https://example.com/customers/{customerId}/orders/{id}
serves the customer who owns the order. The hub delivers a
private update to every token that covers one of its topics:
each added topic widens the audience.
The hub, alternate topics and the cookie are described in our article on Mercure without a BFF. Here, the question is authorization: who may listen to what.
The token follows the extension's rule
The subscriber token is computed from the user, with the extension's rule. The customer listens to their own space, the support team to every order. This computation never copies a list of topics sent by the front, which could ask for another customer's.
The extension and the token thus express the same rule, one in SQL, the other in URL patterns.
The content depends neither on the author nor on the reader
An update is a single message, delivered as is to the whole
audience of its topics. It may only contain what every one
of its recipients is allowed to read. The safest is to put
the IRI alone in it: {"@id": "/orders/{id}"}.
The front then reads the order again over REST, with the extension, the property security and the reader's groups. An order that can no longer be read answers 404, and the front removes it from the screen.
404 or 403: one choice, applied everywhere
RFC 9110 allows a 404 instead of a 403 to hide the existence of a forbidden resource. We answer 404 for another customer's order: the extension removes it from the query, and the provider finds nothing. We answer 403 for an operation reserved for a role, whatever the order.
API Platform's order of execution explains this split. A
security expression that reads
object waits for the provider to load the
order. Without the extension,
object.getCustomer() == user would answer 403
for an existing order and 404 otherwise: the response would
reveal that it exists.
Since API Platform 4.3, an expression that does not use
object is evaluated before the read.
is_granted('ROLE_SUPPORT') therefore answers
403 without querying the database, whether the order exists
or not. securityPostDenormalize, evaluated
after deserialization, checks what a request writes, not
what is broadcast.
The real-time channel follows the same choice. A customer
subscribed to the topic of someone else's order receives no
private update from it. An endpoint issuing a token for a
given order would answer 404, like the GET.
The trade-offs we accept
One read per signal and per tab. Each
signal triggers a GET in every tab that shows
the order. If the load becomes noticeable, the front groups
close signals for the same IRI.
The signal reveals that a change happened. Its audience is the token's, which matches the REST read's. An alternate topic that is too broad, on the other hand, would reveal the activity on other customers' orders.
Two rules to keep aligned. The extension and the token can drift apart when the permissions change. A security test checks them together, role by role.
Publishing per audience remains possible. When the extra read costs too much, we publish the customer view and the support view on two distinct topics. The serialization groups are then set in the publishing code, never inherited from the author's request.
Implementation
The examples use API Platform 5.0, Symfony 7.4, Doctrine ORM
3, the Mercure hub 1.1 with
symfony/mercure-bundle 0.6, and Vue 3. The hub
and cookie configuration stays the one from
the article on Mercure without a BFF.
1. The read rule, in the extension
// src/Doctrine/OrderVisibilityExtension.php
namespace App\Doctrine;
use ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Doctrine\Orm\Extension\QueryItemExtensionInterface;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use App\Entity\Customer;
use App\Entity\Order;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;
final readonly class OrderVisibilityExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
{
public function __construct(private Security $security)
{
}
public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = []): void
{
$this->restrict($queryBuilder, $queryNameGenerator, $resourceClass);
}
public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, ?Operation $operation = null, array $context = []): void
{
$this->restrict($queryBuilder, $queryNameGenerator, $resourceClass);
}
private function restrict(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass): void
{
if (Order::class !== $resourceClass || $this->security->isGranted('ROLE_SUPPORT')) {
return;
}
$customer = $this->security->getUser();
if (!$customer instanceof Customer) {
$queryBuilder->andWhere('1 = 0');
return;
}
$alias = $queryBuilder->getRootAliases()[0];
$parameter = $queryNameGenerator->generateParameterName('customer');
$queryBuilder
->andWhere(\sprintf('%s.customer = :%s', $alias, $parameter))
->setParameter($parameter, $customer);
}
}
The extension filters collections and items, for reads as well as writes. Symfony's autoconfiguration registers it with API Platform.
2. Operations without mercure: true
// src/Entity/Order.php (excerpt)
#[ApiResource(operations: [
new Get(),
new GetCollection(),
// No `object`: evaluated before the read, 403 whether the order exists or not.
new Patch(security: "is_granted('ROLE_SUPPORT')"),
// Custom provider, see step 6.
new Get(uriTemplate: '/orders/{id}/timeline', output: OrderTimeline::class, provider: OrderTimelineProvider::class),
])]
class Order
The mercure attribute goes away: publishing
becomes explicit. With
DTO resources bound by stateOptions, API Platform's listener publishes nothing: the entity is
not a resource.
3. Publish a signal, not the order
// src/Live/OrderLiveListener.php
namespace App\Live;
use App\Entity\Order;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
use Doctrine\ORM\Events;
use Psr\Log\LoggerInterface;
use Symfony\Component\Mercure\Exception\RuntimeException;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
use Symfony\Contracts\Service\ResetInterface;
#[AsEntityListener(event: Events::postPersist, method: 'collect', entity: Order::class)]
#[AsEntityListener(event: Events::postUpdate, method: 'collect', entity: Order::class)]
#[AsDoctrineListener(event: Events::postFlush)]
final class OrderLiveListener implements ResetInterface
{
/** @var array<string, Order> */
private array $changed = [];
public function __construct(
private readonly HubInterface $hub,
private readonly LoggerInterface $logger,
) {
}
public function collect(Order $order): void
{
$this->changed[(string) $order->getId()] = $order;
}
public function postFlush(): void
{
$orders = $this->changed;
$this->reset();
foreach ($orders as $id => $order) {
$update = new Update(
[
// Canonical: the support team's audience.
'https://example.com/orders/'.$id,
// Alternate: the owning customer's audience.
'https://example.com/customers/'.$order->getCustomer()->getId().'/orders/'.$id,
],
// A signal, not the order: the front reads GET /orders/{id} again.
json_encode(['@id' => '/orders/'.$id], \JSON_THROW_ON_ERROR),
private: true,
type: 'order.changed',
);
try {
$this->hub->publish($update);
} catch (RuntimeException $exception) {
$this->logger->warning('Mercure signal not published.', ['exception' => $exception]);
}
}
}
public function reset(): void
{
$this->changed = [];
}
}
The service's publisher token must cover both topics.
postFlush follows the commit, except inside an
enclosing transaction: the article on Mercure without a BFF
covers that case.
4. A token that follows the rule
// src/Live/LiveGrants.php
namespace App\Live;
use App\Entity\Customer;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Mercure\Jwt\Grant;
// Same rule as OrderVisibilityExtension, written as URL patterns.
final readonly class LiveGrants
{
public function __construct(private Security $security)
{
}
/** @return list<Grant> */
public function forCurrentUser(): array
{
if ($this->security->isGranted('ROLE_SUPPORT')) {
return [new Grant([Grant::ACTION_SUBSCRIBE], ['urlpattern' => ['https://example.com/orders/:id']])];
}
$customer = $this->security->getUser();
if (!$customer instanceof Customer) {
return [];
}
$space = 'https://example.com/customers/'.$customer->getId();
return [new Grant([Grant::ACTION_SUBSCRIBE], ['urlpattern' => [$space.'/orders/:id']])];
}
}
The controller that sets the cookie passes these grants to
Authorization::setCookie(). The
:id pattern covers a single segment: a
* wildcard would also cover the topics another
service might later publish under this prefix. The article
on Mercure without a BFF grants the customer's whole space
(/*): it is simpler, but every new topic in it
becomes readable by default.
5. Read again over REST on each signal
// fronts/shop/src/composables/useLiveOrders.ts
import { onScopeDispose, ref } from 'vue';
import { fetchOrder, type OrderView } from '@/api/orders';
const HUB_URL = 'https://mercure.example.com/.well-known/mercure';
export function useLiveOrders(customerId: string) {
const orders = ref(new Map<string, OrderView>());
const url = new URL(HUB_URL);
url.searchParams.append(
'match_urlpattern',
`https://example.com/customers/${customerId}/orders/:id`,
);
const source = new EventSource(url, { withCredentials: true });
source.addEventListener('order.changed', async (event) => {
const { '@id': iri } = JSON.parse(event.data) as { '@id': string };
// The read goes through the extension and the property security.
const order = await fetchOrder(iri); // null on a 404
if (order === null) {
orders.value.delete(iri);
} else {
orders.value.set(iri, order);
}
});
onScopeDispose(() => source.close());
return { orders };
}
With TanStack Query, the signal invalidates the order's key, as in one composable per endpoint.
6. A custom provider goes through the Doctrine provider
An extension only applies to API Platform's Doctrine providers. A custom provider that reads with the repository bypasses it, like the Mercure listener. It therefore delegates the read to the Doctrine provider:
// src/State/OrderTimelineProvider.php
namespace App\State;
use ApiPlatform\Doctrine\Orm\State\ItemProvider;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\ApiResource\OrderTimeline;
use App\Entity\Order;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
/** @implements ProviderInterface<OrderTimeline> */
final readonly class OrderTimelineProvider implements ProviderInterface
{
public function __construct(
// API Platform's Doctrine provider applies OrderVisibilityExtension.
#[Autowire(service: ItemProvider::class)]
private ProviderInterface $itemProvider,
) {
}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?OrderTimeline
{
$order = $this->itemProvider->provide($operation, $uriVariables, $context);
// null: missing or out-of-reach order, API Platform answers 404.
return $order instanceof Order ? new OrderTimeline($order->getId(), $order->getStatusChanges()) : null;
}
}
Checklist
-
No resource published to Mercure without
private: true. - Alternate topics that carry the audience, one space per customer.
- A subscriber token computed from the user, with the extension's rule.
-
Narrow URL patterns (
:id), no wildcard over a shared prefix. - Content reduced to the IRI, or one serialization per audience with groups set in the code.
- A test that publishes a change made by the support team and checks that no internal field gets out.
- A front that reads again over REST on each signal and removes what answers 404.
-
404 for an out-of-reach resource, 403 for an operation
reserved for a role, without
object. - Custom providers that delegate to the Doctrine provider.
Sources
-
API Platform,
Mercure: the
mercureattribute, theprivate,topicsandnormalization_contextoptions. -
API Platform,
PublishMercureUpdatesListener source code: publishing on
postFlush,privateset tofalseby default. - API Platform, source code of AbstractItemNormalizer and ResourceAccessChecker: property security evaluated with the current user.
- API Platform, Extensions: extension interfaces, custom providers.
-
API Platform,
Security with Symfony:
security,securityPostDenormalize, property security. -
API Platform,
CHANGELOG, version 4.3.0 (March 13, 2026):
securityevaluated before the provider when the expression does not useobject. - API Platform, 5.0.0 release notes (September 17, 2026).
-
Mercure,
Authorization: private updates, per-user authorization,
anonymous. - Mercure, Topics and matchers: canonical and alternate topics, URL Patterns.
- IETF, The Mercure Protocol (draft-dunglas-mercure-08, August 11, 2026): the audience of a private update.
- Mercure, release notes 1.0.0 (September 16, 2026) and 1.1.0 (October 8, 2026).
-
Symfony, changelogs of the
Mercure component
(0.8, the
Grantclass) and of the MercureBundle (0.6). - IETF, RFC 9110, section 15.5.4: a 404 to hide the existence of a forbidden resource.
- Lychen, pull request 255: an open-source implementation of the read permissions and published content described here, in a moon monorepo.
- Lychen, pull request 242: an open-source implementation of subscriber tokens built from URL patterns.
- Lychen, pull request 237: an open-source implementation of a provider that goes through the Doctrine extension.