Search code examples
javawebsocketspring-websockethttpsession

Access HTTP Session in WebSocketHandler (Spring-websocket)


Dears, I'm trying to get an HTTPSession in my WebSocketHandler. I could do it successfully when I was using 'javax.websocket-api' but I'm now using 'Spring-Websocket'.

The config :

@ConditionalOnWebApplication
@Configuration
@EnableWebSocket
public class WebSocketConfigurator implements WebSocketConfigurer {

    @Autowired
    private ApplicationContext context;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        MyEndpoint endpoint = context.getBean(MyEndpoint.class);
        registry.addHandler(endpoint, "/signaling");
    }
}

When the connection is established :

    @Component
    public class MyEndpoint implements WebSocketHandler {

        private WebSocketSession wsSession;

        @Override
        public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
            this.wsSession = webSocketSession;
            // need to get the HTTP SESSION HERE        
            log.info("Opening: " + webSocketSession.getId());
        }
    }

And now this is an example of how I could do it using 'javax.websocket-api' :

The configuration :

@ServerEndpoint(value = "/signaling", //
        decoders = MessageDecoder.class, //
        encoders = MessageEncoder.class,
        configurator = MyEndpointConfigurator.class)
/***
 * define signaling endpoint         
 */
public class MyEndpoint extends NextRTCEndpoint {

}

Then I was Injecting the HTTPSession modifying the handshake :

public class MyEndpointConfigurator extends ServerEndpointConfig.Configurator {
    @Override
    public void modifyHandshake(ServerEndpointConfig config,
            HandshakeRequest request,
            HandshakeResponse response) {
        HttpSession httpSession = (HttpSession) request.getHttpSession();
        config.getUserProperties().put(HttpSession.class.getName(), httpSession);
    }
}

And finally, it was accessible when the WS connection was established :

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        this.wsSession = session;
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        log.info("Opening: " + session.getId());

        server.register(session, httpSession);
    }

I could not succeed to do something similar with 'Spring Websocket'. Any solution ? Please do not propose classes from StompJS as I'm not using it.


Solution

  • There is this one to use:

    **
     * An interceptor to copy information from the HTTP session to the "handshake
     * attributes" map to made available via{@link WebSocketSession#getAttributes()}.
     *
     * <p>Copies a subset or all HTTP session attributes and/or the HTTP session id
     * under the key {@link #HTTP_SESSION_ID_ATTR_NAME}.
     *
     * @author Rossen Stoyanchev
     * @since 4.0
     */
    public class HttpSessionHandshakeInterceptor implements HandshakeInterceptor {
    

    And there is a sample in the Reference Manual how to configure it:

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new MyHandler(), "/myHandler")
            .addInterceptors(new HttpSessionHandshakeInterceptor());
    }
    

    So, whatever you need from the HTTP session is going to be available in the WebSocketSession.getAttributes().