Spring boot 内置tomcat禁止不安全HTTP方法

Spring boot 内置tomcat禁止不安全HTTP方法

在tomcat的web.xml中可以配置如下内容,让tomcat禁止不安全的HTTP方法

<security-constraint>  
   <web-resource-collection>  
      <url-pattern>/*</url-pattern>  
      <http-method>PUT</http-method>  
      <http-method>DELETE</http-method>  
      <http-method>HEAD</http-method>  
      <http-method>OPTIONS</http-method>  
      <http-method>TRACE</http-method>  
   </web-resource-collection>  
   <auth-constraint>  
   </auth-constraint>  
</security-constraint>  
<login-config>  
  <auth-method>BASIC</auth-method>  
</login-config>

Spring boot使用内置tomcat,没有web.xml配置文件,可以通过以下配置进行,简单来说就是要注入到Spring容器中

@Configuration
public class TomcatConfig {
 
    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory tomcatServletContainerFactory = new TomcatEmbeddedServletContainerFactory();
        tomcatServletContainerFactory.addContextCustomizers(new TomcatContextCustomizer(){
 
            @Override
            public void customize(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                SecurityCollection collection = new SecurityCollection();
                //http方法
                collection.addMethod("PUT");
                collection.addMethod("DELETE");
                collection.addMethod("HEAD");
                collection.addMethod("OPTIONS");
                collection.addMethod("TRACE");
                //url匹配表达式
                collection.addPattern("/*");
                constraint.addCollection(collection);
                constraint.setAuthConstraint(true);
                context.addConstraint(constraint );
                
                //设置使用httpOnly
                context.setUseHttpOnly(true);
                
            }
        });
        return tomcatServletContainerFactory;
    }
 
}

猜你喜欢

转载自www.cnblogs.com/senlinyang/p/10314525.html