背景
对于一些对安全级别要求高的应用,可能只允许有GET和POST请求,其他请求方式需要禁用,那么可以从多个层面来进行禁用。下面从大范围禁用到小范围禁用罗列如下(假定服务容器是tomcat)
从tomcat层面禁用
从tomcat来禁用,表示tomcat中所有运行的应用都禁用这些请求方法
修改apache-tomcat/conf/web.xml,在<session-config></session-config>
节点后面新增禁用配置:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<security-constraint>
<web-resource-collection>
<web-resource-name>BDC</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
<http-method>HEAD</http-method>
<http-method>TRACE</http-method>
<http-method>OPTIONS</http-method>
</web-resource-collection>
<auth-constraint/>
</security-constraint>
从应用层的web.xml中禁用
- 如果项目含web.xml的传统应用,按照从tomcat层禁用方式一样:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<security-constraint>
<web-resource-collection>
<web-resource-name>BDC</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
<http-method>HEAD</http-method>
<http-method>TRACE</http-method>
<http-method>OPTIONS</http-method>
</web-resource-collection>
<auth-constraint/>
</security-constraint>
- 如果是springboot类型的应用,可以通过增加过滤器来实现,参考下面
从应用层来禁用
传统应用,首先创建一个过滤器类,一般情况可以将这种禁用的写到配置文件来管理,方便灵活修改,本次为了演示,直接用静态块初始化。
import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MethodFilter implements Filter {
private static List<String> FORBIDDEN_METHOD=new ArrayList<String>();
static {
FORBIDDEN_METHOD.add("PUT");
FORBIDDEN_METHOD.add("DELETE");
FORBIDDEN_METHOD.add("HEAD");
FORBIDDEN_METHOD.add("TRACE");
FORBIDDEN_METHOD.add("OPTIONS");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String method=httpRequest.getMethod();
if(FORBIDDEN_METHOD.contains(method)){
((HttpServletResponse) response).setStatus(HttpStatus.SC_FORBIDDEN);
return;
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig)
throws ServletException {
}
@Override
public void destroy() {
}
}
springboot应用类似,核心逻辑都一样。
通过以上几种方式,可以实现不同粒度的禁用某些HTTP请求方法,在应用层面禁用可以更灵活的根据特定的场景来禁用,在应用的web.xml根据特定的url来禁用,在tomcat或jboss层面可以粗粒度的禁用所有应用