首页 文章

尽管在表单中发送CSRF令牌,但不支持Spring Security CSRF 405方法POST

提问于
浏览
2

我使用的是Spring框架版本4.3.5.RELEASE . Spring安全版是4.2.2.RELEASE .

我正面临一个与CSRF有关的奇怪问题 . 每当我提交一个表单(来自JSP文件), Sometimes it works fine, the form gets submitted without error but sometimes after submitting the form 时,它会显示 Http Status 405 ? Method not supported . 我也包含了csrf令牌,它们都隐藏在字段中,并将其作为查询字符串附加在表单's action' s标记中 .

这是我的项目中的示例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
}

The problem is coming random. 它有时有效,有时也无效 . 代码或表单没有变化 . 禁用CSRF不是一种可能的解决方案,因为这是我的客户的一项要求 .

如果有人能够解决,请帮助 .

1 回答

  • 1

    在Spring安全性中,CSRF令牌会在每个会话的基础上生成,并且在您的会话未到期之前保持不变 . 这是一个你不能获得405方法的情况,因为你的会话在某个时间间隔内到期(你可以检查一下) . 其次,如果你使用spring的形式,那么就不需要明确地将标记放在隐藏字段中,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}"> -->
    

相关问题