Magento 2 Experten — Hyvä Theme, Tailwind CSS & SEO aus einer Hand ›

JWT Authorization for Mercure Topics

JWT Authorization for Mercure Topics

~15 Min. Lesezeit Zuletzt aktualisiert am August 8, 2026

Chapter 69 only worked because the hub is GENEROUSLY configured in local development mode – a VALID Mercure JWT is the CORRECT way to restrict subscriptions to AUTHORIZED clients.

Understanding the Mercure JWT

Achtung: IMPORTANT: the Mercure JWT is a COMPLETELY DIFFERENT token than the API authentication token from chapter 49 – BOTH are JWTs, but WITH DIFFERENT secrets (MERCURE_JWT_SECRET instead of the lexik key pair) and DIFFERENT purposes.

The Mercure payload structure

{
  "mercure": {
    "subscribe": ["https://localhost/api/projects/1"],
    "publish": []
  }
}

subscribe lists the topics this client is ALLOWED to SUBSCRIBE to – EXACTLY as ROLE_ADMIN encodes a PERMISSION in a normal JWT (chapter 47), this field encodes the ALLOWED Mercure topics.

Generating a Mercure JWT

api/src/State/Provider/MercureAuthorizationTrait.php
<?php

declare(strict_types=1);

namespace App\Security;

use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;

final class MercureTokenGenerator
{
    public function __construct(
        private readonly string $mercureJwtSecret,
    ) {
    }

    public function generate(array $subscribeTopics): string
    {
        $config = Configuration::forSymmetricSigner(
            new Sha256(),
            InMemory::plainText($this->mercureJwtSecret),
        );

        $token = $config->builder()
            ->withClaim('mercure', ['subscribe' => $subscribeTopics])
            ->getToken($config->signer(), $config->signingKey());

        return $token->toString();
    }
}

lcobucci/jwt (already a dependency of lexik/jwt-authentication-bundle) generates the token PROGRAMMATICALLY – in a REAL application, a state provider would DELIVER this token ALONG WITH fetching a project, so the frontend can use it DIRECTLY.

Mercure hubs USUALLY expect the JWT in a mercureAuthorization cookie (set via Set-Cookie from the Symfony backend) instead of an Authorization header – this COOKIE-based pattern is EXACTLY what allows EventSource to authenticate connections, WITHOUT the browser API needing to support custom headers at all.

curl -k -N -H "Cookie: mercureAuthorization=$MERCURE_TOKEN" \
  'https://localhost/.well-known/mercure?topic=https://localhost/api/projects/1'

Tipp: Block 9 (React) covers in depth HOW the frontend OBTAINS this cookie and how EventSource in the browser (which sends cookies AUTOMATICALLY, UNLIKE fetch/axios without explicit configuration) benefits from it.