Search code examples
javaspringsessionstompspring-websocket

How to get Session Id in Spring WebSocketStompClient?


How to get session id in Java Spring WebSocketStompClient?

I have WebSocketStompClient and StompSessionHandlerAdapter, which instances connect fine to websocket on my server. WebSocketStompClient use SockJsClient.
But I don't know how get session id of websocket connection. In the code with stomp session handler on client side

   private class ProducerStompSessionHandler extends StompSessionHandlerAdapter {
            ...
            @Override
            public void afterConnected(StompSession session, StompHeaders  connectedHeaders) {
            ...
            }

stomp session contains session id, which is different from session id on the server. So from this ids:

DEBUG ... Processing SockJS open frame in WebSocketClientSockJsSession[id='d6aaeacf90b84278b358528e7d96454a...

DEBUG ... DefaultStompSession - Connection established in session id=42e95c88-cbc9-642d-2ff9-e5c98fb85754

I need first session id, from WebSocketClientSockJsSession. But I didn't found in WebSocketStompClient or SockJsClient any method to retrieve something like session id...


Solution

  • To get session id you need to define your own interceptor as below and set the session id as a custom attribute.

    public class HttpHandshakeInterceptor implements HandshakeInterceptor {
    
        @Override
        public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                Map attributes) throws Exception {
            if (request instanceof ServletServerHttpRequest) {
                ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
                HttpSession session = servletRequest.getServletRequest().getSession();
                attributes.put("sessionId", session.getId());
            }
            return true;
        }
    

    Now you can get the same session id in the controller class.

    @MessageMapping("/message")
    public void processMessageFromClient(@Payload String message, SimpMessageHeaderAccessor  headerAccessor) throws Exception {
            String sessionId = headerAccessor.getSessionAttributes().get("sessionId").toString();
    
        }