symfonymercure

JWT key for mercure


I try generate JWT key for Mercure settings

I use this manual

https://medium.com/@stefan.poeltl/instant-realtime-notifications-with-symfony-and-mercure-e45270f7c8a5

for pass myJWTKey JWT is

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjdXJlIjp7InN1YnNjcmliZSI6W10sInB1Ymxpc2giOlsiKiJdfX0.iTVjHoLv9bB-O5RNnTtzOFxIW-YECk2JXZeMekZ4GwA 

I found a token builder ( Signed JSON Web Token )

http://jwtbuilder.jamiekurtz.com/

but I find no setting that generates a correct JWT. How do I do it? What I miss?

I tried generate token for env settings

MERCURE_PUBLISH_URL=http://mercure.dev:3000/.well-known/mercure
# The default token is signed with the secret key: !ChangeMe!
MERCURE_JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjdXJlIjp7InN1YnNjcmliZSI6W10sInB1Ymxpc2giOlsiKiJdfX0.iTVjHoLv9bB-O5RNnTtzOFxIW-YECk2JXZeMekZ4GwA
###< symfony/mercure-bundle ###

This token is for default password in docker-compose

 mercure:
      image: dunglas/mercure
      environment:
        # You should definitely change all these values in production
        - JWT_KEY=myJWTKey
        - DEMO=1
        - ALLOW_ANONYMOUS=1
        - HEARTBEAT_INTERVAL=30s
        - ADDR=:3000

if I change myJWTKey to mysecure pass - how I can generate token?


Solution

  • Just an addition to a great answer by @Daidon. Mercure bundle uses lcobucci/jwt and registers it's factory as a service.

    If you want to generate JWT do the following

    1. Pass the factory as an argument with @mercure.hub.default.jwt.factory (here default is for your hub name)
    2. In your service/controller
    public function generateJwt(LcobucciFactory $factory): string
    {
        return $factory->create(['*']);
    }
    

    UPD: even easier way to get a JWT token

    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\Mercure\Authorization;
    
    public function generateJwt(Request $request, Authorization $authorization): string
    {
        return $authorization->createCookie($request, ['*'])->getValue();
    }