一:傳統(tǒng)Web項目的解決方案:
在tomcat的web.xml配置文件中,對不安全的方法進(jìn)行攔截:
<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>
如果需要禁用TRACE請求绘趋,還需要修改tomcat的server.xml配置文件(在server.xml中先允許TRACE請求岂却,再在web.xml中禁用TRACE):
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" allowTrace="true"
redirectPort="8443" />
二:spring boot的解決方案:
1.眾所周知迎瞧,spring boot的容器是內(nèi)嵌的赞警,是沒有web.xml給我們配置的验辞,所有的配置都是在properties文件中進(jìn)行配置的,所以我們的思路也是在properties文件中增加tomcat的相關(guān)配置唱星。
#解決不安全的HTTP方法漏洞
server.tomcat.port-header=HEAD,PUT,DELETE,OPTIONS,TRACE,COPY,SEARCH,PROPFIND
2.代碼的方式增加tomcat的配置(本人測試上面配置文件方式不生效雳旅,這種方式可以,如有不同看法請留言)间聊,代碼如下:
package com.xzp;
import org.apache.catalina.Context;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.session.SessionAutoConfiguration;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
@SpringBootApplication(exclude = { SessionAutoConfiguration.class })
@EnableZuulProxy
public class ApiGatewayServerApplictation {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayServerApplictation.class, args);
}
//主要是以下代碼:
@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);
}
};
//如果需要禁用TRACE請求攒盈,需添加以下代碼:
tomcat.addConnectorCustomizers(connector -> {
connector.setAllowTrace(true);
});
return tomcat;
}
}