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

时间:2015-07-28 07:26:51

标签: stomp spring-websocket

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

任何帮助表示感谢。

3 个答案:

答案 0 :(得分:11)

您可以在与HandshakeInterceptor握手期间将客户端IP设置为WebSocket会话属性:

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) {          
    }
}

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

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

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

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

答案 1 :(得分:3)

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

答案 2 :(得分:0)

尝试将此信息添加为评论,但 stackoverflow 抱怨评论太长,所以我将其发布为

<块引用>

可以在服务中获取该属性而不通过 SimpMessageHeaderAccessor ?我的意思是类似于注射的东西 HttpServletRequest – 鲨鱼 2015 年 11 月 23 日 15:02

问题。

我能够使用这样的语法实现“接近”的结果:

@MessageMapping("/destination")
@SendTo("/topic/someTopic")
public String send(@Header("simpSessionAttributes") Map<String, Object> sessionAttributes) {
    String clientsAddress = sessionAttributes.get("ip"));
    return "The sender's address is: " + clientsAddress ;
}

我不熟悉消息标题的“simpSessionAttributes”名称的来源,但我注意到,如果我以@Sergi Almar 在此线程中描述的方式放置信息 - 我会得到这样的信息结果。但也许这个名称“simpSessionAttributes”可能取决于某些环境配置或消息框架 idk 的特定实现...

我也不介意将此细化作为@Sergi Almar 答案的一部分。

相关问题