2015-10-06 96 views
0

我的目標是不允許OPTIONS, PUT, DELETE HTTP方法按照安全測試的建議。Spring HandlerInterceptor不捕獲除GET,POST之外的其他方法

INTRO

我有一個Spring應用程序。我確實有嵌入式彈簧安全。

TRY-1

我試圖在web.xml中添加參考<security-constraint> - http://www.techstacks.com/howto/disable-http-methods-in-tomcat.html

這是工作,但它提供了無效的響應頭。

RESPONSE

> Status : 403 
> Allow: GET, HEAD, POST, PUT, DELETE, OPTIONS 

如上所述,允許響應標頭不應該被返回。

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 { 

    } 
} 

編輯

通過

<mvc:interceptors> 
    <bean class="com.HTTPMethodInterceptor" /> 
</mvc:interceptors> 

這preHandle工作在springConfig註冊爲「GET 「和」POST「方法。但它不適用於該方法的其餘部分。

如果我的理解錯誤,請糾正我。如果重複,請原諒我。

+0

你需要它的所有請求,或者只是某些URL?你如何在Spring上下文中註冊這個'HandlerInterceptor'? – luboskrnac

+0

@luboskrnac我需要它的所有URL。 '/ *'會很棒。編輯註冊問題 –

回答

0

我用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

相關問題