Forwarded Headers Example in Spring

Published
Updated

When configuring one or more Spring Boot applications behind a netscaler, load balancer, or reverse proxy, it is possible that the URI’s presented at the browser level do not align with those which are being referenced within Spring.

In such a configuration, it is helpful to have the external URL. Take for example a situation in which you need to perform a redirect. Internally, Spring sees URL as /some-app/animals/cat and it may not align with the external URL /animals/cat. If you were to send an HTTP redirect to an internal URL such as /some-app/animals/cat it would return a 404 error.

Such a situation can arise not only with the URL, but even with SSL configurations where the address externally is configured with https:// vs http:// internally, or if internal and external port numbers do not match.

This is what the X-Forwarded headers intend to solve. They provide details on what the external URL is so we don’t have any problems sending redirects or performing any other action.

Here is a list of all the X-Forwarded headers that will be forwarded in Spring:

  • X-Forwarded-Host
  • X-Forwarded-Port
  • X-Forwarded-Proto
  • X-Forwarded-Prefix
  • X-Forwarded-Ssl
  • X-Forwarded-For

ForwardedHeaderFilter is now Deprecated

As of Spring Web 5.1, the ForwardedHeaderFilter has been deprecated in favor of the ForwardedHeaderTransformer. This is the conventional way of defining a (now deprecated) ForwardedHeaderFilter within Spring-Web using a FilterRegistrationBean:

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

New ForwardedHeaderTransformer Example

If you want your application container (WebSphere, WildFly, Netty, Tomcat, etc.) to automatically resolve x-fowarded headers, you don’t need to do anything, this is the default configuration and is equivalent to the following:

server.forward-headers-strategy=native

If you would like Spring to translate these headers, you can simply add the following line in your properties file and Spring will automatically configure a ForwardedHeaderTransformer bean for you.

server.forward-headers-strategy=framework

Alternatively, you can define this bean yourself with the following:

@Bean
public ForwardedHeaderTransformer forwardedHeaderTransformer() {
    return new ForwardedHeaderTransformer();
}

Stripping x-forwarded-for headers

If you wish to filter or have Spring automatically remove any incoming x-forwarded headers, you can register a ForwardedHeaderTransformer like so:

@Bean
public ForwardedHeaderTransformer forwardedHeaderTransformer() {
    ForwardedHeaderTransformer transformer = new ForwardedHeaderTransformer();
    transformer.setRemoveOnly(true);
    return transformer;
}