websocketspring-websocket

Access Http headers in Spring WebSocket Service


I am trying to access the HTTP headers (from the original https upgrade request) in a spring websocket service.

As I understand it I should be able to do this with a HandshakeInterceptor. I have an interceptor like:

public class WebsocketHandshakeInterceptor implements HandshakeInterceptor {

  public WebsocketHandshakeInterceptor() {
  }

  @Override
  public boolean beforeHandshake(
      final ServerHttpRequest request,
      final ServerHttpResponse response,
      final WebSocketHandler wsHandler,
      final Map<String, Object> attributes) throws Exception {
    if (request instanceof ServletServerHttpRequest) {
      ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
    }
    return true;
  }

  @Override
  public void afterHandshake(
      final ServerHttpRequest request,
      final ServerHttpResponse response,
      final WebSocketHandler wsHandler,
      final Exception exception) {
  }
}

But both the request and servletRequest objects have null headers. Note that I am not after a session cookie, as most of the example, but other headers.

I have a test client which makes a request like this:

  WebSocketClient client = new StandardWebSocketClient();
  WebSocketStompClient stompClient = new WebSocketStompClient(client);

  StompSessionHandler sessionHandler = new TestClientStompSessionHandler(getObjectMapper());

  final WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
  if (StringUtils.isNotBlank(token)) {
    LOGGER.error("Adding header           Authorization: Bearer " + token);
    headers.add("Authorization", "Bearer " + token);
  }

  headers.add("X-Foo", "bar");

  stompClient.connect(url, headers, sessionHandler);

Pretty sure it is adding the headers because if I run via my API Gateway which requires the bearer token then it works (with a valid token)


Solution

  • Sorry, my bad. The headers are populated, just the debugger in Eclipse wasn't showing them. Or I was blind. Or both.

    HttpHeaders headers = request.getHeaders();
    

    gives me what I need.