Spring Websockets STOMP - 获取客户端IP地址

Dam*_*ian 4 stomp spring-websocket

有没有办法获取STOMP客户端IP地址?我正在拦截入站通道,但我看不到任何方法来检查IP地址.

任何帮助赞赏.

Ser*_*mar 13

您可以在握手期间将客户端IP设置为WebSocket会话属性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) {          
    }
}
Run Code Online (Sandbox Code Playgroud)

使用握手拦截器配置端点:

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

并使用标头访问器获取处理程序方法中的属性:

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


sha*_*njo 7

下面的示例已更新以获取确切的远程客户端 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) {
}
}
Run Code Online (Sandbox Code Playgroud)