起因:
安全組針對接口測試提出的要求,需要關閉不安全的請求方法,例如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,2.0版本以前使用如下形式
@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);
}
};
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
本文首發於個人公眾號:河岸飛流,歡迎訂閱
原文鏈接:https://mp.weixin.qq.com/s/bqUwkqZyHQEkWDR9fqEqJA