Springcloudgateway + Nginx反向代理获取客户端IP
spring cloud gateway获取客户端IP
采用elasticsearch获取审计相关的信息,其中获取远程客户端操作观云台的IP地址是从前端的Header中获取的
而客户端发起的请求是通过nginx反向代理的,所以获取客户端IP的解决方案是: 在k8s环境下,UI的POD 的配置的configmap中添加如下配置:
proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme;
以上配置就是在Nginx反向代理的时候,添加一些请求Header。
Host:包含客户端真实的域名和端口号。 X-Forwarded-Proto:表示客户端真实的协议(http还是https)。 X-Real-IP:表示客户端真实的IP X-Forwarded-For:这个Header和X-Real-IP类似,但是它在多层代理时会包含真实客户端及中间每个代理服务器的IP。
获取X-Forwarded-For或者X-Real-IP:
public String getIp(HttpServletRequest request) throws Exception { String ip = request.getHeader("X-Forwarded-For"); if (ip != null){ if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) { int index = ip.indexOf(","); if (index != -1) { return ip.substring(0, index); } else { return ip; } } } ip = request.getHeader("X-Real-IP"); if (ip != null) { if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) { return ip; } } ip = request.getHeader("Proxy-Client-IP"); if (ip != null) { if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) { return ip; } } ip = request.getHeader("WL-Proxy-Client-IP"); if (ip != null) { if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) { return ip; } } ip = request.getRemoteAddr(); return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip; }
请求头的意思:
X-Forwarded-For: 只有通过HTTP代理或者负载均衡(比如Nginx)才会添加该项,格式为X-Forwarded-For:client1,proxy1,proxy2,一般情况下,第一个ip为客户端真实的IP,后面的为经过的代理服务器的IP。 Proxy-Client-IP/WL- Proxy-Client-IP 这个一般是经过apache http服务器的请求才有,用apache http做代理时一般加上Proxy-Client-Ip请求头,而WL-Proxy-Client-IP是他的weblogic插件加上的头。 X-Real-IP nginx代理一般会加上此请求头。
上一篇:
Java架构师技术进阶路线图
下一篇:
浏览器输入URL按回车后,会发生什么?