0
点赞
收藏
分享

微信扫一扫

【springboot过ingress后无法获取X-Forwarded-For头信息】

爱动漫建模 2024-09-11 阅读 17

springboot过ingress后无法获取X-Forwarded-For头信息

一、现象

项目使用spring boot 2.7.18,有个新需求是校验X-Forwarded-For头的所有来源ip合法性,线上环境出现取不到X-Forwarded-For头的问题,本地和测试环境都正常。本地是直接调用,测试环境是nginx转发,线上是k8s并且过了ingress。

结论

  1. ingress默认会忽略X-Forwarded-For,需要手动开启use-forwarded-headers: “true”。
  2. springboot中CloudPlatform对Kubernetes platform的类型进行了识别,如果使用的是内嵌的tomcat,在k8s环境中会自动添加了tomcat的RemoteIpValve,线上环境的httpHeader(x-forwarded-for)只有一个,没有代理ip信息,按RemoteIpValve的逻辑,x-forwarded-for头信息会被删除。
    需要二者配合修改。

修改步骤

ingress

kubectl edit configmaps nginx-configuration -n ingress-nginx

修改文件内容,添加参数:
apiVersion: v1
data:
  compute-full-forwarded-for: "true"
  forwarded-for-header: X-Forwarded-For
  use-forwarded-headers: "true"
....

在这里插入图片描述

springboot

添加springboot全局配置

server:
  forward-headers-strategy: none

排查流程

  1. postman调线上接口,线上取不到X-Forwarded-For头。但是在postman添加请求头X-Forwarded-For后,后端服务就能正确取到。
  2. 网上查资料说需要修改ingress配置。参考
  3. 修改ingress配置后,线上k8s容器抓包,流量显示有X-Forwarded-For头信息,且存在多个ip情况,用逗号隔开。
  4. 用python写一个程序用来取X-Forwarded-For头,打成Docker镜像上传部署到k8s,Python能正常取到X-Forwarded-For信息。问题已经定位到定位到springboot。问题分析参考

本文参考

  1. https://blog.csdn.net/weixin_46887489/article/details/134616471
  2. https://blog.csdn.net/m0_71777195/article/details/127978440
举报

相关推荐

0 条评论