spring-websockets how to send a parameter on open connection

Furquan Ahmed picture Furquan Ahmed · May 25, 2016 · Viewed 7.3k times · Source

I was building a spring boot application for web socket connection using TextWebSocketHandler and overriding handleTextMessage.

But I have a requirement that when the user tries to connect to this endpoint I want to validate using some token. Now I know that I can override afterConnectionEstablished and afterConnectionClosed method but is it possible to get some request param or path param while creating socket connection so that I can store the details that to which user this session belongs.

I was able to do this with JavaEE7 annotations as follows but I am being forced to use Spring :

@ServerEndpoint("/ss/{token}")
public class SocketServerEndpoint {
    @Autowired
    private SService ssService;

    @OnOpen
    public void open(Session session, @PathParam("token")String token) throws SSException {
        ssService.processConnectionRequest(token, session);
    }

    @OnMessage
    public String handleMessage(String message, Session session) {
        ssService.processMessage(message);
        return "message_received";
    }

    @OnClose
    public void close(Session session) {
        ssService.removeSession(session);
    }
}

I am new to Spring Boot and Spring Web Sockets and unable to figure out a way, please help !!!

Answer

Pratap Singh picture Pratap Singh · Jul 23, 2020

You can implement WebSocketConfigurer and override registerWebSocketHandlers method to define your endPoint and then retrieve and put in attributes.

public void registerWebSocketHandlers(WebSocketHandlerRegistry registery) {
    logger.info("websocketHanlder registering Socket Handler .");
    registery.addHandler(new SocketTextHandler(), "ss/{token}").addInterceptors(get);
}

 private HandshakeInterceptor getInter() {
    return new HandshakeInterceptor() {
        @Override
        public boolean beforeHandshake(ServerHttpRequest serverHttpRequest,
                                       ServerHttpResponse serverHttpResponse,
                                       WebSocketHandler webSocketHandler,
                                       Map<String, Object> map) throws Exception {
            logger.info("Request ----------" + serverHttpRequest.getHeaders());

            String path = serverHttpRequest.getURI().getPath();
            logger.info("PATH  " + path);
            int index = path.indexOf("/ss");
            String id = path.substring(index);
            map.put("id", id);
            return true;
        }
  }

After putting it on the map, it can be retrieved from session attributes.