spring - 提交表单时出现 InvalidCsrfTokenException

标签 spring jsp spring-security csrf

我正在基于 spring 的 Web 应用程序(版本 4.1.6.RELEASE,spring security 4.0.0.RELEASE)中工作,并且收到错误 InvalidCsrfTokenException: Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.提交表单后(POST 方法)。根据spring's documentation “Spring Security 会自动为您使用的任何 <form:form> 标签插入 CSRF 表单字段”,那么为什么我会收到此异常?
提前致谢。
这是我的 Spring 安全配置:

<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<http use-expressions="true" disable-url-rewriting="true">
    <headers>
        <frame-options/>
        <xss-protection/>
        <hsts/>
    </headers>
    <csrf/>
    <intercept-url pattern="/welcome" access="isAuthenticated()" />
    <!-- some others urls to intercept -->
    <form-login login-page="/login" default-target-url="/welcome"
            authentication-failure-url="/loginfailed" />
    <logout logout-success-url="/logout" />
    <session-management>
        <concurrency-control max-sessions="1" expired-url="/login" />
    </session-management>
</http>


这是我的表单的定义(不包括它包含的字段):

<form:form action="myaction" method="post" enctype="multipart/form-data" id="formId" modelAttribute="myBean">
</form:form>

任何帮助将不胜感激

最佳答案

出现此问题是因为您使用的是多部分表单。请在此处查看已接受的答案:

Spring CSRF token does not work, when the request to be sent is a multipart request

关于spring - 提交表单时出现 InvalidCsrfTokenException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31124859/

相关文章:

java - Spring : how to replace constructor-arg by annotation?

grails - 如何使用spring-security-core-ldap插件在grails中实现LDAP认证?

grails - 使用grail-spring安全插件登录后如何重定向

java - Spring服务无法启动

spring - 如何在不使用任何 XML 文件的情况下设置 Spring Web 服务?

java - 当另一个任务完成执行时,在一定时间后安排任务

java - Java Bean 的使用

maven - 如何使用Maven创建JSP + Servlet + TOMCAT + MySQL

jsp - 如果已经登录,则从 login.jsp 重定向

java - SpringBoot,如何在不使用ldif的情况下使用LDAP进行身份验证?