How to set custom Http header "server" for Spring Boot applications

11,034

Solution 1

You can set custom headers using the StaticHeadersWriter in your Security config, here's a Java config example:

public class SecurityConfig extends WebSecurityConfigurerAdapter {
  protected void configure(HttpSecurity http) throws Exception {
    http
      .headers()
        .addHeaderWriter(new StaticHeadersWriter("Server","here to serve you"))
      ....
  }
  ...
}

Solution 2

FYI, in the latest versions of Spring Boot you can simply set the "server.server-header" property to achieve the same.

Solution 3

You can add additional headers (or overwrite existing ones) with your custom Filter implementation. For example:

@Bean
public Filter myFilter() {
    return new Filter() {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            final HttpServletResponse res = (HttpServletResponse) servletResponse;
            res.addHeader("Server", "my very custom server");

            filterChain.doFilter(servletRequest, servletResponse);
        }

        @Override
        public void destroy() {

        }
    };
}

Solution 4

If you do not use Spring Security you can use TomcatEmbeddedServletContainerFactory and add a TomcatConnectorCustomizer:

@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
    tomcat.setTomcatConnectorCustomizers(Collections.singletonList(c -> c.setProperty("Server", "Pleased to serve you")));
    return tomcat;
}
Share:
11,034
Thomas Jäckle
Author by

Thomas Jäckle

Project Lead and Commiter of Eclipse Ditto: https://github.com/eclipse/ditto

Updated on June 18, 2022

Comments

  • Thomas Jäckle
    Thomas Jäckle almost 2 years

    By default the HTTP "server" header for Spring Boot applications with embedded Tomcat is:

    Server → Apache-Coyote/1.1
    

    How can it in Spring Boot be achieved to use another (custom) "server" header?

    For Tomcat itself, it can be configured at the <Connector> element in XML via the server attribute:

    From https://tomcat.apache.org/tomcat-8.0-doc/security-howto.html#Connectors :

    The server attribute controls the value of the Server HTTP header. The default value of this header for Tomcat 4.1.x to 8.0.x is Apache-Coyote/1.1. This header can provide limited information to both legitimate clients and attackers.

    But attackers will still know that this is a Tomcat server.