How to disable specific headers in Spring Boot

Viewed 121

Is it possible to disable following headers in Spring Boot?

X-Forwarded-Host: 
X-Host: 
X-Forwarded-Server:

Following did not work for me

class MyFilter extends OncePerRequestFilter {
    @Override
    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
            public void setHeader(String name, String value) {
                if (!name.equalsIgnoreCase("X-Forwarded-Host")) {
                    super.setHeader(name, value);
                }
            }
        });
    }
2 Answers

Let's try to have a look broader and start to think about request-response lifecycle.

Once a request has been initiated by a client, there are sort of stops and layers that the request/response goes through between client and the application. There might be a firewall, load-balancer, reverse proxy, middleware etc. On the other hand, based on the application server which serves the application, those headers might be added as well. If there is a mechanism which adds or removes or rewrites the headers apart from the application, those headers should have been managed out of the application.

That being said, if headers were added by the application, they could have been managed within the application. But if headers were added by another stop or layer, they should have been managed in a particular configuration.

Apart from the headers in general, if we think about these specific headers: Based on my general experience, the headers you provided are added when there is a reverse proxy between client and application.

You can leverage more information about them: https://httpd.apache.org/docs/2.4/mod/mod_proxy.html#x-headers

To sum up, you should be managing those headers according to how and why they have been added.

If you want to disable all default headers you can do the folowing:

@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // ...
            .headers(headers -> headers
                // do not use any default headers unless explicitly listed
                .defaultsDisabled()
                .cacheControl(withDefaults())
            );
        return http.build();
    }
}

To disable specific ones you can follow the same strategy.

Reference: https://docs.spring.io/spring-security/reference/5.8/servlet/exploits/headers.html#page-title

Related