在Websocket上通过Nginx转发用户IP

时间:2018-11-07 08:45:37

标签: java nginx websocket

我将this Websocket library中的示例用于here,以基于websocket创建多个服务。

接受请求的主要服务器是Nginx服务器,该服务器根据请求的来源(基于域)转发请求,因此我可以确定接收到的请求是针对Websocket的。

问题出在这里

public void onOpen(WebSocket ws, ClientHandshake handshake) {
    System.out.println("-------------------------------");
    System.out.println(ws.getRemoteSocketAddress());
    System.out.println("-------------------------------");
}

getRemoteSocketAddress 将始终返回nginx服务器IP,例如 /192.168.1.100:43556

我的nginx配置是:

server{
    listen 80;
    server_name we.mydomain.com;
    access_log /var/log/nginx/access-ws-debug.log;
    error_log /var/log/nginx/error-ws-debug.log;

    set_real_ip_from  192.168.1.0/24;
    real_ip_header X-Real-IP;
    real_ip_recursive on;

    location / {
       proxy_pass http://192.168.1.101:54321;

       proxy_http_version 1.1;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header Host $http_host; #host
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header Y-Real-IP $realip_remote_addr;

       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection "Upgrade";

       proxy_connect_timeout 1d;
       proxy_send_timeout 1d;
       proxy_read_timeout 1d;
    }
}

nxing配置是否有问题?还是有其他方法可以将用户的IP获取到websocket后面?


已解决,感谢Mark的回答。以下代码与提到的库无关。这是没有任何库的jsp中的“经典” Web实现。

我将握手修改为如下形式:

@Override
public void modifyHandshake(
        ServerEndpointConfig config,
        HandshakeRequest request,
        HandshakeResponse response
) {
    HttpSession httpSession = (HttpSession) request.getHttpSession();
    config.getUserProperties().put(HttpSession.class.getName(), httpSession);
    config.getUserProperties().put("Headers",request.getHeaders());
}

要获取标题,只需在OnOpen中调用它即可

@OnOpen
public void onOpen(final Session session, EndpointConfig config){ //This happens when javascript opens socket session
    Object list = config.getUserProperties().get("Headers");
    System.out.println("-------------------------------------");
    System.out.println(list);
    System.out.println("-------------------------------------");
}

标题的返回格式如下(使用我的手机)

{upgrade=[websocket], 
accept-language=[en-US,en;q=0.9,es;q=0.8], 
cookie=[JSESSIONID=0BAE99DFDE5DD81D20CFF04E4257D7FE], 
sec-websocket-extensions=[permessage-deflate; client_max_window_bits], 
origin=[https://mywebsite.com], 
x-forwarded-for=[1.2.3.4], 
sec-websocket-version=[13], 
pragma=[no-cache], 
x-real-ip=[1.2.3.4], 
y-real-ip=[1.2.3.4], 
host=[mywebsite.com], 
connection=[Upgrade], 
sec-websocket-key=[ZroOewrBGrg660x7ocI+nog==], 
cache-control=[no-cache], 
accept-encoding=[gzip, deflate, br], 
user-agent=[Mozilla/5.0 (Linux; Android 8.0.0; SM-N950F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36]}

该IP在我所在的地区可以进行地理位置定位。

1 个答案:

答案 0 :(得分:2)

这不是一件容易的事,但是您的配置看起来不错,您只需要从设置的标头(X-Real-IP中获得原始IP。

import javax.websocket.*;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;

@ServerEndpoint(value = "/test", configurator = Test.TestConfiguratior.class)
public class Test extends Endpoint {

    @Override
    public void onOpen(Session session, EndpointConfig endpointConfig) {
        Object o = endpointConfig.getUserProperties().get(TestConfiguratior.HEADER_NAME);
        //o should be the string object you are looking for
    }

    @OnMessage
    public void onMessage(Session session, String msg) {
        //do what u want
    }

    public static class TestConfiguratior extends ServerEndpointConfig.Configurator {
        static String HEADER_NAME = "X-Real-IP";

        @Override
        public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
            String firstFoundHeader = request.getHeaders().get(HEADER_NAME.toLowerCase()).get(0);
            sec.getUserProperties().put(HEADER_NAME, firstFoundHeader);
        }
    }
}

TL.DR .:您可以使用javax.websocket.EndpointConfig#getUserProperties映射将数据放入其中并在以后检索。最初,我认为这可能会在使用此确切代码时引起一些并发问题,但是我无法重现它。甚至文档也建议这样做: https://javaee.github.io/tutorial/websocket010.html

更新: :这是一个JSR 356示例,并不专门针对上述框架。