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请求头中获取相关信息了。

相关推荐
五仁火烧13 小时前
Vue3 项目的默认端口行为
服务器·vue.js·nginx·容器·vue
oMcLin15 小时前
如何在 RHEL 7 上优化 Nginx 与 PHP‑FPM 配置,确保高并发 Web 应用的稳定性与响应速度?
前端·nginx·php
鲨莎分不晴16 小时前
Nginx 部署前端项目实战指南
运维·前端·nginx
知南x16 小时前
【STM32MP157 视频监控项目】(2) 移植 Nginx
stm32·nginx·音视频
GDAL18 小时前
NGINX njs 全解析:从基础配置到高级特性实战
nginx·njs
报错小能手19 小时前
nginx集群聊天室(一) 初步讲解集群聊天室所需库的搭建
c++·nginx
ICT董老师20 小时前
通过kubernetes部署nginx + php网站环境
运维·nginx·云原生·容器·kubernetes·php
bleach-21 小时前
buuctf系列解题思路祥讲--[SUCTF 2019]CheckIn1--文件上传以及user.ini的应用
nginx·web安全·网络安全·php
CodeCaptain21 小时前
配置Nginx反向代理来实现负载均衡,续阿里云ECS配置Nginx反向代理
nginx·阿里云·负载均衡
r***01381 天前
Nginx代理到https地址忽略证书验证配置
运维·nginx·https