I have Spring Data Rest with Hateoas as my backed. It is behind a proxy.
Backend url: backend.com
Proxy url: proxy.com
When I query proxy url, e.g. http://proxy.com/items/1
, I get a response with href
links with domain backend.com
. I need the domain to be proxy.com
.
With HATEOAS, a client interacts with a network application whose application servers provide information dynamically through hypermedia. A REST client needs little to no prior knowledge about how to interact with an application or server beyond a generic understanding of hypermedia.
Spring HATEOAS provides common abstractions (representational models, a Link class, API to build links pointing to Spring MVC controllers, etc.) to ease building hypermedia driven REST APIs with Spring MVC in general. Thus, you can use it alongside Spring MVC to manually build those services.
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.
Inspired by the comment from Cyril Gambis, Spring offers a property server.use-forward-headers
, which exists at least from 1.3.0.RELEASE. From Spring Boot 2.2.0.RELEASE, that property is deprecated, use server.forward-headers-strategy
instead.
When you use Spring Data Rest, I suggest set server.forward-headers-strategy = framework
, then Spring Hatoaes generates the proxied URI for href with the help of x-forwarded-*
headers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With