Search code examples
springjspspring-securitycsrf

InvalidCsrfTokenException when submitting a form


I'm working in a spring based web application (version 4.1.6.RELEASE, spring security 4.0.0.RELEASE) and I'm getting the error InvalidCsrfTokenException: Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'. after submitting a form (POST method). According to the spring's documentation "Spring Security automatically inserts a CSRF form field for any <form:form> tags you use", so why I'm getting this exception?
Thanks in advance.
This is my spring security configuration:

<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>


And this is the definition of my form (excluding the fields it contains):

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

Any help will be appreciated


Solution

  • The issue is arising because you are using a multi-part form. Please see the accepted answer here:

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