Real-Time APIs · Scaling Real-Time Systems
Authentication and Authorization for Real-Time
Auth at connect, per-channel authorization and token expiry.
Authenticate during the handshake (session cookie with Origin check, or a short-lived token obtained via an authenticated HTTP call), authorize every subscription (can this user join room 42?), and re-check permissions when they change (kick users removed from a room). Long-lived connections outlive access tokens: require periodic re-authentication or close connections when tokens/sessions are revoked.
Real-time auth practices
| Concern | Approach |
|---|---|
| Browser auth | Session cookie + Origin check, or short-lived ticket in query/first message |
| Token in URL | Short-lived one-time ticket only (URLs get logged) |
| Subscriptions | Authorize each channel join server-side |
| Permission changes | Revoke subscriptions; push 'removed' event |
| Token expiry | Re-auth message before expiry or disconnect |
1. Client: POST /realtime/tickets (authenticated) → {"ticket": "rt_9f…", "expires_in": 30}
2. Client: new WebSocket("wss://rt.example.com/ws?ticket=rt_9f…")
3. Server: validate + consume ticket (one-time), bind user to connection
4. Client: {"type":"subscribe","channel":"room:42"} → server checks membership → ok / error 403
5. Server: on membership revoked → {"type":"unsubscribed","channel":"room:42"}
Common pitfalls
- Long-lived access tokens in WebSocket URLs (logged by proxies).
- Authorizing only at connect time.
- Connections staying alive after logout or permission removal.
Key points
- Auth at handshake (tickets/cookies)
- Authorize every channel
- Handle revocation and expiry
Further reading: Heroku: WebSocket security
Practice questions
Why use a short-lived one-time ticket instead of the access token in a WebSocket URL?
Answer
URLs are logged by proxies and servers; a one-time, seconds-long ticket limits exposure if logged.
Why must channel subscriptions be authorized individually?
Answer
Being authenticated doesn't mean a user may see every room or user stream; each subscription is a separate access decision.
Open in the app to mark lessons complete, take notes and track your progress.