Video in progress
The browser WebSocket API doesn't let you add an Authorization header. How do you authenticate the connection then?
There are three common ways: a session or token in a cookie (it goes with the handshake automatically), a short-lived one-time ticket in a query parameter, or, with STOMP, the token in the CONNECT frame header. Putting a long-lived JWT in the URL is a bad idea.
📖 Answer
new WebSocket(url, protocols) takes only a URL and a subprotocol, with no arbitrary headers. The options:
Cookie. If the app already uses a session cookie, the cookie goes along with the handshake and Spring Security recognizes the user as usual. This is the simplest way, but because of the CSRF-like attack (CSWSH), an Origin check is mandatory.
Ticket. The client first gets a one-time 30-second ticket with an ordinary REST request (Authorization: Bearer ...), then connects with wss://host/ws?ticket=abc. The server checks the ticket and deletes it. Even if the URL ends up in access logs, the ticket is already useless.
STOMP CONNECT. The handshake goes through anonymously, and the token travels in the first frame:
const client = new Client({
brokerURL: 'wss://example.uz/ws',
connectHeaders: { Authorization: `Bearer ${token}` }
});
The server checks it in a ChannelInterceptor and binds the user to the session.
Some people stuff the token into the Sec-WebSocket-Protocol header. It works, but that header has a different purpose and the server has to echo it back in the response, so it's a confusing solution.
Sign up to mark studied questions and save your progress.