我正在使用Spring框架版本4.3.5.RELEASE。
Spring安全性版本是4.2.2.RELEASE。

我面临与CSRF相关的奇怪问题。每当我提交表单(来自JSP文件)时,有时它可以正常工作,该表单被提交而没有错误,但是有时在提交表单之后,它显示 Http Status 405?方法不支持。我也将csrf token 包括在隐藏字段中,并将其作为查询字符串附加到表单的动作标签中。

这是我的项目中的POST表单示例:

 <form:form class="form-horizontal" method="POST" modelAttribute="dealerVisit" enctype="multipart/form-data"
        action="http://localhost:8080/update/edit.html?${_csrf.parameterName}=${_csrf.token}">

        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}">
</form:form>

这是我要提交上述表格的控制器:
@RequestMapping(value = "/update/edit.html", method = RequestMethod.POST)
    public String saveEdit(ModelMap map, @Valid @ModelAttribute(MODEL_KEY) DealerVisitVO dealerVisitVO, BindingResult result,
            @RequestParam(required = false, name="followup") Boolean followup) {
//my codes here
}

问题即将来临。 有时有效,有时无效。无需更改代码或形式。禁用CSRF是不可能的解决方案,因为这是我的客户的一项要求。

如果有人能够解决,请提供帮助。

最佳答案

在Spring Security中,CSRF token 是按会话生成的,并且保持不变,直到您的会话没有过期。这是一种情况,您不允许使用405方法,因为您的会话每隔一段时间就会过期(您可以检查一下)。其次,如果您使用的是Spring表单,则无需将 token 显式放置在隐藏字段中,Spring默认情况下会执行此操作,也无需将其放入查询字符串中。您的代码应该是这样的...

<form:form class="form-horizontal" method="POST" modelAttribute="dealerVisit" enctype="multipart/form-data" action="http://localhost:8080/update/edit.html">

     <!-- Spring will add by default -->
    <!-- <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"> -->

09-30 12:43
查看更多