Search code examples
sessionwebsocketspring-websockethttpsession

Understanding timeouts in websocket sessions


websocket session is wrapped in a http session and so when the http session timesout the websocket session also times out.

However, when only the first call is a http call which is based on session cookie and the rest of the time it is a direct established connection, how does the connection ever close in case of a timeout?

Scenario - We have a reverse proxy that manages the validation check on the sessions. This means it intercepts each call and checks for the validity of the session. In case the cookies have expired, it returns a 401.

Since I have integrated websockets to this system, the initial websocket call goes through this reverse proxy with a valid cookie, upgrades the request to websocket and thereafter keeps sending messages directly. The reverse proxy is not aware of these direct messages sent over WS.

Now when the http session expires, the other calls being made to the system get a 401. However the WS connection above does not know about it at all and continues to send/receive messages.

In case of a logout, an invalidate is called on the http session and so all the bound objects are notified and I get a SessionDisconnectEvent. However in case of timeouts I have no indication at all. How should I terminate the WS connection in such cases?

Stack - spring + sockJS + basic stomp


Solution

  • My observations are that all the websocket sessions that are bound to the http session are not terminated in case of logout. Only the one that initiated the logout gets the SessionDisconnectMessage.

    In case of timeouts, there are no indications at all.

    To handle timeouts, I make a call to the server soon after I get a message at the client side and look for a 401 on this call. If it returns a 401, I initiate a session close on the client side.

    To handle logout, I maintain a map of the http session id and all the websocket sessions associated with it. When I receive a disconnect on any of the websocket sessions, I terminate all the other ws sessions associated with that http session.