HttpHiddenMethodFilter导致双重检查csrf标记

时间:2016-12-12 10:50:34

标签: java spring spring-mvc servlet-filters

我尝试使用HiddenHttpMethodFilter来允许我的Spring MVC应用程序处理PUTDELETE个请求。以下是我的web.xml过滤器的一部分:

<filter> 
<filter-name>httpMethodFilter</filter-name> 
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 
</filter> 

<filter-mapping> 
<filter-name>httpMethodFilter</filter-name> 
<url-pattern>/*</url-pattern> 
</filter-mapping> 

<filter> 
<filter-name>springSecurityFilterChain</filter-name> 
<filter-class>org.springframework.web.filter.DelegatingFilterProxy 
</filter-class> 
</filter> 

<filter-mapping> 
<filter-name>springSecurityFilterChain</filter-name> 
<url-pattern>/*</url-pattern> 
</filter-mapping>

但是此配置会导致请求重复检查。例如。我发送PUT请求,然后我在调试器中看到HiddenHttpMethodFilter实际执行了,控制器方法成功执行更新并返回200,但随后在DispatcherServlet或FrameworkServlet中的某处返回以下错误:

HTTP Status 405 - Request method 'PUT' not supported

I can see that method was executed in debugger only; "Network" tab shows 405 only

可能我的过滤器配置不正确?如何避免双重过滤?

控制器方法的代码可能会澄清smth:

@RequestMapping(method = RequestMethod.PUT, value = "/update")  
public ModelAndView update(@ModelAttribute("entity") @Valid Entity entity) { 
    ModelAndView model = new ModelAndView(); 
    service.update(entity); 
    model.setViewName("/blog/success"); 
    model.addObject("record", entity); 
    return model; 
} 

1 个答案:

答案 0 :(得分:0)

是的,确实上面评论中描述的解决方案很有帮助。我通过以下方式将控制器方法从视图渲染更改为重定向:

@RequestMapping(method = RequestMethod.PUT, value = "/update")  
public String update(@ModelAttribute("entity") @Valid Entity entity) {
            service.update(entity);
            return "redirect:desiredMethod"; 
//desiredMethod is GET method that renders needed page
        } 

现在它可以正常使用了!