gpt4 book ai didi

java - 尽管以表单形式发送 CSRF token ,但不支持 Spring Security CSRF 405 方法 POST

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:49:28 34 4
gpt4 key购买 nike

我正在使用 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>

这是我提交上述表格的 Controller :

@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 在每个 session 基础上生成并保持不变,直到您的 session 未过期。这是您收到 405 方法不允许的一种情况,因为您的 session 将在某个时间间隔到期(您可以检查一下)。其次,如果您使用的是 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}"> -->

关于java - 尽管以表单形式发送 CSRF token ,但不支持 Spring Security CSRF 405 方法 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46231871/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com