Spring Websockets STOMP - get client IP address

六月ゝ 毕业季﹏ 提交于 2019-12-05 02:42:29

问题


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.


回答1:


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<String, Object> 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");
    ...
}



回答2:


Below example updated to get the exact remote client ip:

@Component
public class IpHandshakeInterceptor implements HandshakeInterceptor {

   @Override
   public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
    // Set ip attribute to WebSocket session
    if (request instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
        String ipAddress = servletRequest.getServletRequest().getHeader("X-FORWARDED-FOR");
        if (ipAddress == null) {
            ipAddress = servletRequest.getServletRequest().getRemoteAddr();
        }
        attributes.put("ip", ipAddress);
    }
    return true;
}

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


来源:https://stackoverflow.com/questions/31669927/spring-websockets-stomp-get-client-ip-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!