Irina
Irina

Reputation: 1309

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

Upvotes: 14

Views: 29590

Answers (3)

dimirsen Z
dimirsen Z

Reputation: 891

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

Upvotes: 5

Dhiraj Ray
Dhiraj Ray

Reputation: 837

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

    }

Upvotes: 19

Arseniy
Arseniy

Reputation: 688

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

Upvotes: 24

Related Questions