Video in progress

How do you get the client's IP address, User-Agent or a handshake query parameter inside a WebSocket or STOMP handler?

These exist only during the handshake (the HTTP request), so a HandshakeInterceptor reads them and writes them to the session attributes. Afterward you get them with session.getAttributes() in a raw handler, or SimpMessageHeaderAccessor.getSessionAttributes() in STOMP.

📖 Answer

After the handshake there's no HTTP request, only frames. So you have to save what you need at that single moment:

class ClientInfoInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest req, ServerHttpResponse res,
                                   WebSocketHandler h, Map<String, Object> attrs) {
        attrs.put("ip", req.getRemoteAddress().getAddress().getHostAddress());
        attrs.put("ua", req.getHeaders().getFirst(HttpHeaders.USER_AGENT));
        String room = UriComponentsBuilder.fromUri(req.getURI())
                .build().getQueryParams().getFirst("room");
        if (room != null) attrs.put("room", room);
        return true; // returning false rejects the handshake
    }

    @Override
    public void afterHandshake(ServerHttpRequest req, ServerHttpResponse res,
                               WebSocketHandler h, Exception ex) { }
}
registry.addEndpoint("/ws").addInterceptors(new ClientInfoInterceptor());

In a STOMP controller:

@MessageMapping("/chat.send")
void send(ChatMessage m, SimpMessageHeaderAccessor acc) {
    String ip = (String) acc.getSessionAttributes().get("ip");
}

If you need HTTP session attributes, there's a ready-made HttpSessionHandshakeInterceptor that copies them into the WebSocket attributes.

Behind a load balancer, getRemoteAddress() gives the proxy's IP. In Spring Boot, setting server.forward-headers-strategy=native (or framework) makes it take X-Forwarded-For into account. If you read the header by hand, trust only the value set by your own proxy; a client can forge it however it likes.

Don't store heavy objects in the attributes: with 100,000 connections, an extra kilobyte on each turns into a hundred megabytes.