13

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...

Irina
  • 939
  • 1
  • 8
  • 26

3 Answers3

23

You can use @Header annotation to access sessionId:

@MessageMapping("/login")
public void login(@Header("simpSessionId") String sessionId) {
    System.out.println(sessionId);
}

And it works fine for me without any custom interceptors

Arseniy
  • 628
  • 1
  • 6
  • 8
18

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();

    }
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Dhiraj Ray
  • 827
  • 7
  • 11
  • Thank you! Due to the server works with javascript client too, I send session id to java client by it's request. – Irina Feb 16 '17 at 15:05
  • 2
    Instead of writing your own interceptor you could make use of the built-in [`HttpSessionHandshakeInterceptor`](https://docs.spring.io/spring-framework/docs/5.0.0.RELEASE/javadoc-api/org/springframework/web/socket/server/support/HttpSessionHandshakeInterceptor.html). – izstas Oct 14 '17 at 18:49
  • Also it gets me the id from the initial "GET /info" request for the websocket, vs something that looks much different with the custom HandshakeInterceptor implementation above. – Ryan Pelletier Sep 19 '20 at 17:56
5

There is a way to extract sockjs sessionId via Reflection API:

public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
    // we need another sessionId!
    System.out.println("New session established : " + session.getSessionId());
    DefaultStompSession defaultStompSession =
            (DefaultStompSession) session;
    Field fieldConnection = ReflectionUtils.findField(DefaultStompSession.class, "connection");
    fieldConnection.setAccessible(true);

    String sockjsSessionId = "";
    try {
        TcpConnection<byte[]> connection = (TcpConnection<byte[]>) fieldConnection.get(defaultStompSession);
        try {
            Class adapter = Class.forName("org.springframework.web.socket.messaging.WebSocketStompClient$WebSocketTcpConnectionHandlerAdapter");
            Field fieldSession = ReflectionUtils.findField(adapter, "session");
            fieldSession.setAccessible(true);
            WebSocketClientSockJsSession sockjsSession = (WebSocketClientSockJsSession) fieldSession.get(connection);
            sockjsSessionId = sockjsSession.getId(); // gotcha!
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    if (StringUtils.isBlank(sockjsSessionId)) {
        throw new IllegalStateException("couldn't extract sock.js session id");
    }

    String subscribeLink = "/topic/auth-user" + sockjsSessionId;
    session.subscribe(subscribeLink, this);
    System.out.println("Subscribed to " + subscribeLink);
    String sendLink = "/app/user";
    session.send(sendLink, getSampleMessage());
    System.out.println("Message sent to websocket server");
}

Can be seen here: tutorial

dimirsen Z
  • 873
  • 13
  • 16