Mercure-Hub: Authentication of subscribers
This documentation is part of the Getting started guide. View the full guide here: How to get started with Mercure-hub.
👋 Welcome to the Stackhero documentation!
Stackhero offers a ready-to-use Mercure-Hub cloud solution that provides a host of benefits, including:
- Unlimited requests and message sizes.
- Customizable domain name secured with HTTPS (for example, https://real-time.your-company.com).
- Effortless updates with just a click.
- Optimal performance and robust security powered by a private and dedicated VM.
- Available in 🇪🇺 Europe and 🇺🇸 USA.
Save time and simplify your life: it only takes 5 minutes to try Stackhero's Mercure-Hub cloud hosting solution!
In the earlier examples, subscribers were not authenticated and you needed to allow "anonymous subscribers" on the Stackhero dashboard.
To authenticate subscribers, you generate a JWS (JSON Web Signature) using the 'Subscriber JWT key' defined in the Stackhero dashboard. The JWS is then sent using either browser cookies or the authorization header.
Since the Server-Sent Events API does not support custom header definitions, cookies must be used. However, using cookies implies that your Mercure-hub server and client need to share the same domain (or subdomain).
If you wish to use SSE across different domains, consider an EventSource polyfill that allows header definitions. One option is available at https://github.com/Yaffle/EventSource.
First, generate a JWS for your client on your server side. An example is available in backend/subscriberJwsGenerator.js. Simply input your subscriber JWT and run the script using node subscriberJwsGenerator.js.
Then, on the front end, in the file frontend/subscriberWithAuthorization.html, fill in your endpoint and the generated JWS. Open the file in your browser and Mercure-hub will now work with authentication!
Don't forget to uncheck "Allow anonymous subscribers" in the Stackhero dashboard!