Api-platform and Mercure

Spread the love

This was an interesting one for me. It took me quite a while to clearly get the private subscriptions. Here is what it was in the end:

AuthenticationSuccessListener

    public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event): void
    {
        $data = $event->getData();
        $user = $event->getUser();

        if (!$user instanceof User) {
            return;
        }

        $token = (new Builder())
            ->withClaim('mercure', ['subscribe' => $user->getMercureIri()])
            ->sign(new Sha256(), 'my_secret_key')
            ->getToken();

        $data['mercureToken'] = $token->__toString();

        $event->setData($data);
    }

User Entity

public function getMercureIri(): array
{
return ['api/users/'.$this->getId()];
}

Remember you need to register the listener in your services.yml but thats about it! Now when you login, you get a Mercure Token which you save, and when you try to subscribe from front end, pass that token… and there it is.

NOTE:

I wasted a few hours because I forgot to destroy the old token on logout, so other users were using the token. Don’t forget to destroy token 🙂

Leave a Reply

Your email address will not be published.