我的目标是不允许OPTIONS, PUT, DELETE
安全测试建议的 HTTP 方法。
简介
我有一个 Spring 申请。我确实在其中嵌入了 Spring Security。
TRY-1
我尝试添加 <security-constraint>
在 web.xml 中引用 - http://www.techstacks.com/howto/disable-http-methods-in-tomcat.html
这是有效的,但它提供了无效的响应 header 。
回应
> Status : 403
> Allow: GET, HEAD, POST, PUT, DELETE, OPTIONS
如前所述,不应返回 Allow 响应 header 。
TRY-2
所以我尝试添加 HandlerInterceptor
public class HTTPMethodInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
if (request.getMethod().equalsIgnoreCase("options") ||
request.getMethod().equalsIgnoreCase("put")||
request.getMethod().equalsIgnoreCase("delete")) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized Request");
return false;
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
}
}
编辑
在springConfig中注册
<mvc:interceptors>
<bean class="com.HTTPMethodInterceptor" />
</mvc:interceptors>
此预句柄适用于“GET”和“POST”方法。但它不适用于该方法的其余部分。
如果我的理解有误,请纠正我。如果重复,请原谅。
最佳答案
我使用 CSRF
请求匹配器来实现这个技巧,效果很好。
如下创建请求匹配器
public class SecurityRequestMatcher implements org.springframework.security.web.util.matcher.RequestMatcher {
public static final String OPTIONS = "options";
public static final String DELETE = "delete";
public static final String PUT = "PUT";
@Override
public boolean matches(HttpServletRequest request) {
if (request.getMethod().equalsIgnoreCase(OPTIONS) ||
request.getMethod().equalsIgnoreCase(DELETE)||
request.getMethod().equalsIgnoreCase(PUT)) {
return true;
}
return false;
}
}
Spring 配置为
<bean id="securityRequestMatcher"
class="com.SecurityRequestMatcher"/>
<security:http>
<security:csrf request-matcher-ref="securityRequestMatcher"/>
</security:http>
还有宾果游戏 :D
关于java - Spring HandlerInterceptor 不捕获 GET、POST 以外的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32966774/