【发布时间】:2020-03-26 08:00:50
【问题描述】:
我的带有 Spring Web MVC 的 Spring Boot 2.2.0 应用程序在反向代理后面运行。 Spring 如何正确处理X-Forwarded-{Prefix,Host,Proto}-headers 以识别对服务器发出的实际请求?
【问题讨论】:
我的带有 Spring Web MVC 的 Spring Boot 2.2.0 应用程序在反向代理后面运行。 Spring 如何正确处理X-Forwarded-{Prefix,Host,Proto}-headers 以识别对服务器发出的实际请求?
【问题讨论】:
对于 Spring Boot ForwardedHeaderFilter-Bean。从 Spring Boot 2.2.0 开始,您不必再这样做了。只需将server.forward-headers-strategy=NATIVE 或server.forward-headers-strategy=FRAMEWORK 添加到您的application.properties 文件中即可。
NATIVE 表示 servlet 容器(例如 undertow、tomcat)正在解析 x-forwarded-*-headers,这在大多数情况下都很好。如果您依赖X-Forwarded-Prefix,则必须使用FRAMEWORK,以便正确设置request.getContextPath()。
例子:
https://mydomain.tld/my-microservice/actuator
reverse-proxy 像这样转发请求:
// Forwarded-Request from Reverse Proxy to your microservice
GET http://localhost:8080/actuator/
X-Forwarded-Host: mydomain.tld
X-Forwarded-Proto: https
X-Forwarded-Prefix: /my-microservice
调试到 HttpServletRequest 将导致:
request.getRequestURL(): "https://mydomain.tld/my-microservice/actuator/"
request.getScheme(): "https"
request.getContextPath(): "/my-microservice"
new UrlPathHelper().getPathWithinApplication(request): "/actuator"
【讨论】:
server.forward-headers-strategy=FRAMEWORK 除非您知道自己在做什么,即除非您信任您的反向代理。恶意客户端可以添加他们想要的任何标头,然后... KABOOM。
forwarded headers 已被代理添加并且可以信任或被恶意客户端信任?这个安全考虑也被强调了here
framework 级别forward-headers-strategy 并添加一个入口标签nginx.ingress.kubernetes.io/x-forwarded-prefix: "${k8s_app_path}",其中该变量是应用程序正在通过的前缀。