springcloud gateway转发后getServerName被更改的问题

该问题起源于一次将代码移植到微服务产生。当使用springcloud gateway更换掉nginx网关后,出现无法登录的情况,跟进发现转发的信息里丢失了Host

=== MimeHeaders ===
accept = */*
knife4j-gateway-code = ROOT
content-type = application/x-www-form-urlencoded
user-agent = Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36
request-origion = Knife4j
origin = http://localhost:7003
sec-fetch-site = same-origin
sec-fetch-mode = cors
sec-fetch-dest = empty
referer = http://localhost:7003/doc.html
accept-encoding = gzip, deflate, br
accept-language = zh-CN,zh;q=0.9
cookie = oxygentk=99d0a1b10bdd1443589a3416184d31984ed81136535c2e6498edbae12728f748; oxygenuid=36AB9A653683D50D4EC7E525BD9C96E9; charge-key={%22userId%22:3603%2C%22name%22:%22%E6%96%B0%E6%89%8B3603%E5%95%8A%22%2C%22icon%22:%22https://whalesing-web.oss-cn-guangzhou.aliyuncs.com/appres/forbidden.png%22}; AWX_RISK_ID=f6f3dd72e6cee7611eddf8328462756df97853ca; Hm_lvt_5819d05c0869771ff6e6a81cdec5b2e8=1684128760; Hm_lpvt_5819d05c0869771ff6e6a81cdec5b2e8=1684129236; lang=zh-CN; i_like_gogs=f529fa5db09e7bdd; JSESSIONID=20A183584BD3512F939D5696D56DA14A
forwarded = proto=http;host="localhost:7003";for="[0:0:0:0:0:0:0:1]:1926"
x-forwarded-for = 0:0:0:0:0:0:0:1
x-forwarded-proto = http
x-forwarded-prefix = /biz-core
x-forwarded-port = 7003
x-forwarded-host = localhost:7003
host = 192.168.1.196:8083
content-length = 0

上面看到host信息已经变成ip地址,而原地址被放到了x-forwarded-host。

因为request.getHeaders()会优先获得Host的Header,导致了request.getHeaders()的结果和原信息不一致。解决办法有两种

1)单独获得x-forwarded-for头部信息

2)设置gateway按原头部进行转发。添加参数PreserveHostHeader:

bootstrap.yml

server:
  port: 7003
spring:
  application:
    name: gateway
  cloud:
    nacos:
      default-filters:
        - PreserveHostHeader #发送原主机头
      discovery:
        namespace: public
        server-addr: 192.168.1.196:8848
相关推荐
BothSavage1 天前
Knife4j在Gateway下的URI优化以及热刷新
windows·gateway
武子康1 天前
Java-33 深入浅出 Spring - FactoryBean 和 BeanFactory BeanPostProcessor
java·开发语言·后端·spring·springboot·springcloud
希忘auto1 天前
详解Redis的常用命令
redis·1024程序员节
yaosheng_VALVE2 天前
探究全金属硬密封蝶阀的奥秘-耀圣控制
运维·eclipse·自动化·pyqt·1024程序员节
dami_king2 天前
SSH特性|组成|SSH是什么?
运维·ssh·1024程序员节
壹佰大多2 天前
【spring-cloud-gateway总结】
java·spring·gateway
龙哥·三年风水2 天前
workman服务端开发模式-应用开发-后端api推送修改二
分布式·gateway·php
龙哥·三年风水2 天前
workman服务端开发模式-应用开发-后端api推送修改一
分布式·gateway·php
Hello Dam2 天前
面向微服务的Spring Cloud Gateway的集成解决方案:用户登录认证与访问控制
spring cloud·微服务·云原生·架构·gateway·登录验证·单点登录
小笨猪-3 天前
统⼀服务⼊⼝-Gateway
java·spring cloud·微服务·gateway