I've been really struggling with how to manage authorization when using WebSockets. I have a WebSocket server that needs to communicate with other services on behalf of a user. Typically, I rely on JWTs hidden behind an API Gateway or Backend For Frontend (BFF) for token exchange or forwarding. However, I'm not comfortable exposing JWTs to the front end through WebSockets. What's the best approach here? Should I send the JWT anyway? Maybe use some long-lived self-issued token (like for an hour)? Alternatively, I could set up mutual TLS (mTLS) for service communication, but that doesn't really help with the user-specific authorization. I'm just feeling quite confused about the best practices here.
5 Answers
In my case, since I have a dedicated backend API, the JWT gets passed with every request anyway, so it’s not much of an issue for me.
I suggest using very short-lived tokens, like 5 minutes or even less, and set it up to request a new token from the API if the connection drops.
You could also have the client send a cookie with the token along with the initial connection request, just like any regular request.
You really don’t need a token that lasts longer than the WebSocket connection itself. Once you’ve established the connection, you have an authenticated link with the user. So, focus on using a short-lived token solely for the initial authentication. After that, you can associate the user ID with the socket server-side. Just make sure you’re using a TLS-encrypted connection (wss://), since that keeps things secure similar to any other request from the user's browser. The WebSocket server can validate the token upon connection and drop the connection if it’s invalid.
Exactly! Just use a short-lived token to establish the connection. You could even pre-validate the token during the initial upgrade request to prevent invalid tokens from establishing the socket in the first place. Plus, I’ve used the `Sec-WebSocket-Protocol` header to send the token since that’s the only header available during a socket request, although it might not be the best method.

Related Questions
How to Build a Custom GPT Journalist That Posts Directly to WordPress
Cloudflare Origin SSL Certificate Setup Guide
How To Effectively Monetize A Site With Ads