最近查看项目日志,发现一些HEAD,TRACE等类似的restful方法来请求接口,经了解这些请求是由爬虫或者不法程序用来做探测的,为了防患于未然,决定在项目中将这些不用的restful方法屏蔽掉,屏蔽方式分为两种,第一种是在对应的应用程序中配置,第二种是在反向代理或网关中做配置
应用程序配置
在Springboot程序中,如果使用的是Tomcat的话可以按照下面代码进行配置(Jetty容器类似),代码如下:
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TomcatConfig {
@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("TRACE");
collection.addMethod("COPY");
collection.addMethod("LOCK");
collection.addMethod("UNLOCK");
collection.addMethod("SEARCH");
collection.addMethod("MKCOL");
collection.addMethod("CONNECT");
collection.addMethod("MOVE");
collection.addMethod("PROPFIND");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
});
return factory;
}
}
上面的代码保留了get、post、delete、put、option方法,如果项目只需要这些方法的话可以将上面的代码放到项目中即可。
nginx代理配置(推荐)
在server块中加上配置,如下,
if ($request_method !~* GET|POST|DELETE|PUT|OPTIONS) {
return 444;
}
上述代码意思是当request_method不等于GET|POST|DELETE|PUT|OPTIONS中的任意一个值时,将返回444错误。
完整代码配置如下;
server {
listen 80;
server_name xxxx.xxxx.com;
if ($request_method !~* GET|POST|DELETE|PUT|OPTIONS) {
return 444;
}
location / {
...
...
}
}