How to set up custom server header for Spring boot applications

By default, the HTTP server header for Spring applications to download with built-in Tomcat is:

Server β†’ Apache-Coyote/1.1 

How to do this in Spring Boot to use a different (custom) server header?

For Tomcat itself, it can be configured in 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 HTTP server header. The default value for this header for Tomcat 4.1.x to 8.0.x is Apache-Coyote / 1.1. This header may provide limited information to both legitimate clients and attackers.

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

+5
source share
4 answers

You can set custom headers using StaticHeadersWriter in your security config, here is a sample Java configuration:

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

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

 @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() { } }; } 
+3
source

If you are not using Spring Security, you can use TomcatEmbeddedServletContainerFactory and add TomcatConnectorCustomizer:

 @Bean public EmbeddedServletContainerFactory servletContainer() { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(); tomcat.setTomcatConnectorCustomizers(Collections.singletonList(c -> c.setProperty("Server", "Pleased to serve you"))); return tomcat; } 
+2
source

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

+2
source

Source: https://habr.com/ru/post/1233172/


All Articles