Spring Websockets STOMP - get client IP address

后端 未结 3 2002
孤街浪徒
孤街浪徒 2021-02-08 21:21

Is there any way to obtain STOMP client IP address? I am intercepting inbound channel but I cannot see any way to check the ip address.

Any help appreciated.

3条回答
  •  既然无缘
    2021-02-08 22:08

    You could set the client IP as a WebSocket session attribute during the handshake with a HandshakeInterceptor:

    public class IpHandshakeInterceptor implements HandshakeInterceptor {
    
        public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                WebSocketHandler wsHandler, Map attributes) throws Exception {
    
            // Set ip attribute to WebSocket session
            attributes.put("ip", request.getRemoteAddress());
    
            return true;
        }
    
        public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                WebSocketHandler wsHandler, Exception exception) {          
        }
    }
    

    Configure your endpoint with the handshake interceptor:

    @Override
    protected void configureStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").addInterceptors(new IpHandshakeInterceptor()).withSockJS();
    }
    

    And get the attribute in your handler method with a header accessor:

    @MessageMapping("/destination")
    public void handlerMethod(SimpMessageHeaderAccessor ha) {
        String ip = (String) ha.getSessionAttributes().get("ip");
        ...
    }
    

提交回复
热议问题