How to cope with x-forwarded-headers in Spring Boot 2.2.0? (Spring Web MVC behind reverse proxy)

社会主义新天地 提交于 2020-03-19 06:05:09

问题


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?


回答1:


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 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.


Example:

  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
    

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"


来源:https://stackoverflow.com/questions/59126518/how-to-cope-with-x-forwarded-headers-in-spring-boot-2-2-0-spring-web-mvc-behin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!