一、背景
起因:安全组针对接口测试提出的要求,需要关闭不安全的请求方法,例如 put、delete 等方法,防止服务端资源被恶意篡改。
用过 springMvc 都知道可以使用 @PostMapping、@GetMapping 等这种注解限定单个接口方法类型,或者是在 @RequestMapping 中指定 method 属性。这种方式比较麻烦,那么有没有比较通用的方法,通过查阅相关资料,答案是肯定的。
二、tomcat 传统形式
通过配置web.xml达到禁止不安全的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
1、2.0 版本以前使用如下形式
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
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);
}
}
2、2.0 版本使用以下形式
@Bean
public ConfigurableServletWebServerFactory configurableServletWebServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addContextCustomizers(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 factory;
}
关于内嵌tomcat的更多配置,感兴趣可以阅读以下官方文档。
参考链接:https://docs.spring.io/spring-boot/docs/2.0.0.RC1/reference/htmlsingle/#howto-configure-tomcat
原文链接:springboot禁用内置Tomcat的不安全请求方法
作者:河岸飞流
转载仅为方便学习查看,一切权利属于原作者,本人只是做了整理和排版,如果带来不便请联系我删除。
最后修改:2020-05-04 06:34:35
© 著作权归作者所有
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付

发表评论