【问题标题】:How to set custom Http header "server" for Spring Boot applications如何为 Spring Boot 应用程序设置自定义 Http 标头“服务器”
【发布时间】:2016-01-04 20:55:38
【问题描述】:
默认情况下,带有嵌入式 Tomcat 的 Spring Boot 应用程序的 HTTP“服务器”标头是:
Server → Apache-Coyote/1.1
如何在 Spring Boot 中实现使用另一个(自定义)“服务器”标头?
对于 Tomcat 本身,可以通过 server 属性在 XML 中的 <Connector> 元素中进行配置:
来自https://tomcat.apache.org/tomcat-8.0-doc/security-howto.html#Connectors:
服务器属性控制服务器 HTTP 标头的值。 Tomcat 4.1.x 到 8.0.x 的此标头的默认值为 Apache-Coyote/1.1。此标头可以为合法客户端和攻击者提供有限的信息。
但攻击者仍然会知道这是一个 Tomcat 服务器。
【问题讨论】:
标签:
spring
tomcat
spring-security
spring-boot
【解决方案1】:
您可以在安全配置中使用StaticHeadersWriter 设置custom headers,这是一个Java 配置示例:
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.headers()
.addHeaderWriter(new StaticHeadersWriter("Server","here to serve you"))
....
}
...
}
【解决方案2】:
您可以使用自定义的 Filter 实现添加其他标题(或覆盖现有标题)。例如:
@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】:
如果你不使用 Spring Security,你可以使用 TomcatEmbeddedServletContainerFactory 并添加一个 TomcatConnectorCustomizer:
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.setTomcatConnectorCustomizers(Collections.singletonList(c -> c.setProperty("Server", "Pleased to serve you")));
return tomcat;
}
【解决方案4】:
仅供参考,在最新版本的 Spring Boot 中,您只需设置“server.server-header”属性即可实现相同目的。