How to configure Spring HATEOAS behind proxy?

亡梦爱人 提交于 2019-11-27 23:06:48

As of Spring-Boot 2.1 / Spring 5.1, Spring shifts the responsibility of handling X-Forwarded-* from Spring HATEOAS to Spring MVC.

https://jira.spring.io/browse/SPR-16668

You now require the registration of a filter bean.

Minimal implementation:

@Bean
FilterRegistrationBean<ForwardedHeaderFilter> forwardedHeaderFilter()
{
    FilterRegistrationBean<ForwardedHeaderFilter> bean = new FilterRegistrationBean<>();
    bean.setFilter(new ForwardedHeaderFilter());
    return bean;
}

Make sure your proxy is adding X-Forwarded-Host: proxy.com header to the request that is passed to backend.com. Then Spring Hateoas will automatically generate link hrefs with proxy.com.

X-Forwarded-Host can contain port.

Also see other X-Forwarded-* headers, which are supported too.

Though this has been answered by Mariano, I wanted to add that it works for Spring Boot. However, if you don't use Spring Boot and instead use Spring 5.1.X in a traditional web application deployed within J2EE container (like mine), you will need to add a filter to your web application's web.xml similar to below:

    <filter>
    <filter-name>forwardedHeaderFilter</filter-name>
    <filter-class>org.springframework.web.filter.ForwardedHeaderFilter</filter-class>
    <init-param>
        <param-name>relativeRedirects</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>forwardedHeaderFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Besides this, you will also need to upgrade Hateoas to version 0.25.1 where this issue has been fixed from Hateoas side.

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