1、传统Web项目的解决方案
在不使用spring boot的情况下,有两种解决方案1、在过滤器中进行拦截,对于不是http安全的方法直接给前端返回错误信息;2、在tomcat的web.xml配置,对不安全的方法进行拦截。下面,我们重点说下第二种方案,因为这种方案对所有可能存在此安全漏洞的系统都启作用,不用在每个系统中都进行处理。在tomcat的web.xml配置文件中,加如如下的配置文件:
[html] view plain copy
- <security-constraint>
- <web-resource-collection>
- <url-pattern>/*</url-pattern>
- <http-method>HEAD</http-method>
- <http-method>PUT</http-method>
- <http-method>DELETE</http-method>
- <http-method>OPTIONS</http-method>
- <http-method>TRACE</http-method>
- <http-method>COPY</http-method>
- <http-method>SEARCH</http-method>
- <http-method>PROPFIND</http-method>
- </web-resource-collection>
- <auth-constraint>
- </auth-constraint>
- </security-constraint>
加入这个配置之后,每当我们请求服务器资源的时候,会对请求进行拦截,然后只允许安全的HTTP方法过去。
2、spring boot的解决方案
方案1:
众所周知,spring boot的容器是内嵌的,是没有web.xml给我们配置的,所有的配置都是在properties文件中进行配置的,所以我们的思路也是在properties文件中增加tomcat的相关配置
[java] view plain copy
- #解决不安全的HTTP方法漏洞
- server.tomcat.port-header=HEAD,PUT,DELETE,OPTIONS,TRACE,COPY,SEARCH,PROPFIND
关于tomcat的其他配置,有兴趣的可以自己查阅官网。
方案2:
代码的方式增加tomcat的配置,代码如下:
[java] view plain copy
- @Configuration
- public class TomcatConfig {
- @Bean
- public EmbeddedServletContainerFactory servletContainer() {
- TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {// 1
- protected void postProcessContext(Context context) {
- SecurityConstraint securityConstraint = new SecurityConstraint();
- securityConstraint.setUserConstraint("CONFIDENTIAL");
- SecurityCollection collection = new SecurityCollection();
- collection.addPattern("/*");
- collection.addMethod("HEAD");
- collection.addMethod("PUT");
- collection.addMethod("DELETE");
- collection.addMethod("OPTIONS");
- collection.addMethod("TRACE");
- collection.addMethod("COPY");
- collection.addMethod("SEARCH");
- collection.addMethod("PROPFIND");
- securityConstraint.addCollection(collection);
- context.addConstraint(securityConstraint);
- }
- };
- return tomcat;
- }
- }
这两种方式其实是等同的。个人认为第一种方式更简单灵活。