从8.0.23版本开始,tomcat支持在它自带的web.xml里配置HttpHeaderSecurityFilter,这是一个可选项,默认不开启该filter,开启后可支持的配置项如下:
<!-- ================== Built In Filter Definitions ===================== --> <!-- A filter that sets various security related HTTP Response headers. --> <!-- This filter supports the following initialization parameters --> <!-- (default values are in square brackets): --> <!-- --> <!-- hstsEnabled Should the HTTP Strict Transport Security --> <!-- (HSTS) header be added to the response? See --> <!-- RFC 6797 for more information on HSTS. [true] --> <!-- --> <!-- hstsMaxAgeSeconds The max age value that should be used in the --> <!-- HSTS header. Negative values will be treated --> <!-- as zero. [0] --> <!-- --> <!-- hstsIncludeSubDomains --> <!-- Should the includeSubDomains parameter be --> <!-- included in the HSTS header. --> <!-- --> <!-- antiClickJackingEnabled --> <!-- Should the anti click-jacking header --> <!-- X-Frame-Options be added to every response? --> <!-- [true] --> <!-- --> <!-- antiClickJackingOption --> <!-- What value should be used for the header. Must --> <!-- be one of DENY, SAMEORIGIN, ALLOW-FROM --> <!-- (case-insensitive). [DENY] --> <!-- --> <!-- antiClickJackingUri IF ALLOW-FROM is used, what URI should be --> <!-- allowed? [] --> <!-- --> <!-- blockContentTypeSniffingEnabled --> <!-- Should the header that blocks content type --> <!-- sniffing be added to every response? [true] --> <!-- <filter> <filter-name>httpHeaderSecurity</filter-name> <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class> <async-supported>true</async-supported> </filter> -->
如可以设置只允许同源请求的配置项如下:
<filter> <filter-name>httpHeaderSecurity</filter-name> <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class> <init-param> <param-name>antiClickJackingOption</param-name> <param-value>SAMEORIGIN</param-value> </init-param> <async-supported>true</async-supported> </filter> <filter-mapping> <filter-name>httpHeaderSecurity</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
另外,需要注意的是Spring Security中也有类似的配置项,如果使用Spring Security框架需要注意的是该框架默认设置 X-Frame-Options: DENY
如下图所示:
上图来自官方文档说明(4.0.1)
Tomcat的HttpHeaderSecurityFilter配置项会覆盖Spring Security的配置。
时间: 2024-10-28 11:52:30