如何处理 Spring Boot 2.2.0 中的 x-forwarded-headers?(反向代理背后的Spring Web MVC) [英] How to cope with x-forwarded-headers in Spring Boot 2.2.0? (Spring Web MVC behind reverse proxy)

查看:23
本文介绍了如何处理 Spring Boot 2.2.0 中的 x-forwarded-headers?(反向代理背后的Spring Web MVC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的带有 Spring Web MVC 的 Spring Boot 2.2.0 应用程序在反向代理后面运行.Spring 如何正确处理 X-Forwarded-{Prefix,Host,Proto}-headers 以识别向服务器发出的实际请求?

My Spring Boot 2.2.0 application with Spring Web MVC is running behind a reverse proxy. How can Spring cope properly with X-Forwarded-{Prefix,Host,Proto}-headers to recognize the actual request made to the server?

推荐答案

对于 Spring Boot <= 2.1.x,您必须提供一个 ForwardedHeaderFilter-Bean.从 Spring Boot 2.2.0 开始,您不必再这样做了.只需将 server.forward-headers-strategy=NATIVEserver.forward-headers-strategy=FRAMEWORK 添加到您的 application.properties 文件.

With Spring Boot <= 2.1.x you had to provide a ForwardedHeaderFilter-Bean. Since Spring Boot 2.2.0 you don't have to do this anymore. Just add server.forward-headers-strategy=NATIVE or server.forward-headers-strategy=FRAMEWORK to your application.properties-file.

NATIVE 意味着 servlet 容器(例如 undertow、tomcat)正在解析 x-forwarded-*-headers,这在大多数情况下都很好.如果您依赖 X-Forwarded-Prefix,则必须使用 FRAMEWORK 以便 request.getContextPath() 正确设置.

NATIVE means that the servlet container (e.g. undertow, tomcat) is resolving the x-forwarded-*-headers which is fine in most cases. If you rely on X-Forwarded-Prefix than you must use FRAMEWORK so that request.getContextPath() is set properly.

示例:

  1. 用户在浏览器中输入:https://mydomain.tld/my-microservice/actuator
  2. 微服务my-microservice"(例如user-service)应处理请求;它在本地主机上运行:8080
  3. 反向代理像这样转发请求:

  1. User types into browser: https://mydomain.tld/my-microservice/actuator
  2. the microservice "my-microservice" (e.g. user-service) shall handle the request; it's running on localhost:8080
  3. reverse-proxy forwards the request like this:

// 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 将导致:

Debugging into a HttpServletRequest will result in:

request.getRequestURL(): "https://mydomain.tld/my-microservice/actuator/"
request.getScheme(): "https"
request.getContextPath(): "/my-microservice"
new UrlPathHelper().getPathWithinApplication(request): "/actuator"

这篇关于如何处理 Spring Boot 2.2.0 中的 x-forwarded-headers?(反向代理背后的Spring Web MVC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆