SpringCloud使用Nginx代理、Gateway网关以后如何获取用户的真实ip

前言

本文转载自: www.microblog.store,且已获得授权.

一、需求背景

微服务架构使用了Nginx代理转发、并且使用了SpringCloud的Gateway统一控制所有请求,现在有个需求: 做一个日子记录切面,需要记录用户请求的ip地址

在上述双重背景下,通过普通的方法获取用户ip地址是不可行的,只能获取到引用部署所在服务器的内网地址,必须要做一系列的设置以后才能正确获取到响应的地址。

二、解决办法

2.1 Nginx设置

css 复制代码
  location / { 
      root /opt/xxx/xxx-auth; 
      index  index.html index.htm; 
      try_files $uri $uri/ /index.html; 
      
     # 获取用户请求ip
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;  #获取客户端真实IP
      proxy_set_header REMOTE-HOST $remote_addr;
  }

2.2 gateway网关设置

java 复制代码
@Component
@Log4j2
public class AuthenticationFilter implements GlobalFilter, Ordered {
    /**
     * 验证请求头是否带有Authentication
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getPath().pathWithinApplication().value();

        Optional.of(exchange.getRequest()).ifPresent(item -> {
            // 获取客户端IP地址
            List<String> xForwardedFor = item.getHeaders().get("x-forwarded-for");
            List<String> xRealIp = item.getHeaders().get("x-real-ip");
            List<String> remoteHost = item.getHeaders().get("remote-host");
            response.getHeaders().add("X-Forwarded-For", (xForwardedFor == null || xForwardedFor.isEmpty()) ? "" :
                    xForwardedFor.get(0));
            response.getHeaders().add("X-Real-IP", (xRealIp == null || xRealIp.isEmpty()) ? "" : xRealIp.get(0));
            response.getHeaders().add("Remote-Host", (remoteHost == null || remoteHost.isEmpty()) ? "" :
                    remoteHost.get(0));
        });

        //身份认证等等....
        
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

通过上述设置以后,我们就能正常在request请求头中获取相关信息了。

相关推荐
大G哥5 小时前
记一次K8S 环境应用nginx stable-alpine 解析内部域名失败排查思路
运维·nginx·云原生·容器·kubernetes
妍妍的宝贝5 小时前
k8s 中微服务之 MetailLB 搭配 ingress-nginx 实现七层负载
nginx·微服务·kubernetes
叶北辰CHINA8 小时前
nginx反向代理,负载均衡,HTTP配置简述(说人话)
linux·运维·nginx·http·云原生·https·负载均衡
Lansonli10 小时前
云原生(四十八) | Nginx软件安装部署
nginx·云原生·ecs服务器
加油,旭杏16 小时前
【中间件学习】fastCG介绍和使用
学习·nginx·fastcgi
攸攸太上19 小时前
Spring Gateway学习
java·后端·学习·spring·微服务·gateway
苹果醋319 小时前
大模型实战--FastChat一行代码实现部署和各个组件详解
java·运维·spring boot·mysql·nginx
tanxiaomi1 天前
vue 不是spa 单页面应用吗? 配置路由工作模式为history 后 ,为什么配置Nginx的 try_files 可以根据url 找到对应的文件?
前端·vue.js·nginx
twins35201 天前
配置Nginx以支持通过HTTPS回源到CDN
网络·nginx·https
astuv1 天前
在树莓派上部署开源监控系统 ZoneMinder
linux·nginx·树莓派·监控·摄像头·zoneminder·apache2