Video in progress
A WebSocket connection opened with a JWT lives for hours, but the token expires in 15 minutes. How do you handle this?
If the token is checked only at the handshake or CONNECT, an expired or revoked user keeps receiving messages for hours. The usual solution is to store the token's expiry in the session, ask the client for a new token when it expires, and close the connection if none arrives.
📖 Answer
This problem doesn't exist in REST, because there every request rechecks the token. In WebSocket the check happens once. As a result, a user gets blocked, loses a role or changes their password, but confidential data keeps arriving in their open tab.
The scheme I use:
- The token is validated at
CONNECT, andexpis written to a session attribute. - When the client refreshes its token, it sends a special message:
SEND /app/auth.refreshwith the new token. The server validates it and updatesexpin the session. - An inbound interceptor checks
expon every message (or a scheduler checks every minute); if it has passed, the session is closed:
if (Instant.now().isAfter(expiresAt)) {
// the client sees this and does a login or refresh
session.close(CloseStatus.POLICY_VIOLATION.withReason("token expired"));
}
Here session is the raw WebSocketSession. With STOMP, to get at it you register sessions through a WebSocketHandlerDecoratorFactory.
So you don't have to wait when a user is blocked, you should also listen for a "logout/ban" event and close all of that user's sessions right away. With many instances, that event has to reach every instance through pub/sub.
There's a simpler option too: force the connection to be reopened every 15 to 30 minutes. If the client's reconnect logic is good, the user doesn't notice, and the server does a full check with a fresh token every time.
Sign up to mark studied questions and save your progress.