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

问题描述 投票:3回答:1

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

我正面临一个与CSRF有关的奇怪问题。每当我提交一个表单(来自JSP文件),有时它工作正常,表单提交没有错误但有时在提交表单后,它显示Http状态405?方法不受支持。我也包含了csrf标记,它们都隐藏在字段中,并将其作为查询字符串附加在表单的action标记中。

这是我的项目中的示例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不是一种可能的解决方案,因为这是我的客户的一项要求。

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

java spring spring-security csrf-protection http-status-code-405
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}"> -->

© www.soinside.com 2019 - 2024. All rights reserved.