Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Security and hardening

POST requests return 403 in Spring Security because the CSRF token is missing

Error403 Forbidden on POST, PUT, PATCH or DELETE while GET works

Short answer

Spring Security checks a CSRF token on every request except GET, HEAD, TRACE and OPTIONS. A 403 with a missing token means the client sent none, or the app is a stateless API that should not use CSRF at all. Send the token from the form or header, or exempt the API paths.

  • Applies to Spring Boot 3.5, Spring Security 6.5, Java 21
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Send the failing request with curl and read the status line. Then turn on debug logging for the CSRF filter so the log tells you whether a token arrived at all.

    curl -i -X POST http://localhost:8080/api/orders -H "Content-Type: application/json" -d '{}'
    # application.properties
    logging.level.org.springframework.security.web.csrf=DEBUG
  2. 2Match what you see, then jump to its fix

    1. 1Only form POSTs fail; GET pages load fineA plain HTML form does not carry the tokenFix
    2. 2fetch or axios POST returns 403 while the same call from the browser form worksA JavaScript client sends no token headerFix
    3. 3Every non-GET call from Postman, mobile apps or other servers returns 403A stateless token API is still behind CSRF protectionFix
    4. 4The first POST after signing in or out fails, later ones work after a page reloadThe token was cleared by login or logout and the client kept the old oneFix

What does the error look like?

  • 403 Forbidden on POST, PUT, PATCH or DELETE while GET works
  • MissingCsrfTokenException
  • InvalidCsrfTokenException
  • Invalid CSRF token found for http://localhost:8080/...

Cause 1 of 4

A plain HTML form does not carry the token

1Check

Open the page source and look for a hidden field named _csrf inside the form. Thymeleaf and the Spring form tags add it for you; static HTML or hand-built forms do not.

curl -s http://localhost:8080/login | grep -i _csrf

2Fix

Render the form through Thymeleaf or the Spring form tags so the hidden field is added. In a view technology that does not do this, print the token from the _csrf request attribute yourself.

<form th:action="@{/orders}" method="post">
  <button type="submit">Save</button>
</form>
<!-- JSP fallback -->
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

3Verify

Reload the page, check that the hidden input is present, and submit the form.

curl -s http://localhost:8080/orders/new | grep -i _csrf

Confirmed by docs.spring.io

Did this fix it?

Cause 2 of 4

A JavaScript client sends no token header

1Check

Look at the request headers in the browser network tab. There should be an X-CSRF-TOKEN header (token repository in the session) or an X-XSRF-TOKEN header (cookie repository).

curl -i -c jar.txt http://localhost:8080/ | grep -i set-cookie

2Fix

For a single-page app, store the token in a cookie that JavaScript can read, and let the client copy it into the header. For pages rendered by the server, put the token and header name in meta tags and read them in your script.

http.csrf(csrf -> csrf
    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()));

3Verify

Repeat the POST with the header set and confirm a non-403 status.

curl -i -b jar.txt -X POST http://localhost:8080/api/orders \
  -H "X-XSRF-TOKEN: <value of the XSRF-TOKEN cookie>"

Confirmed by docs.spring.io

Did this fix it?

Cause 3 of 4

A stateless token API is still behind CSRF protection

1Check

Ask whether browsers ever send these requests with a session cookie. If clients authenticate with an Authorization header only, there is no cookie for an attacker to ride on.

grep -rn "csrf" src/main/java

2Fix

Ignore CSRF for the API paths only, or disable it when the whole backend serves no browser traffic.

http.csrf(csrf -> csrf
    .ignoringRequestMatchers("/api/**"));
// or, for an app with no browser clients at all
// http.csrf(csrf -> csrf.disable());

3Verify

Restart the app and repeat the POST that failed.

curl -i -X POST http://localhost:8080/api/orders -H "Content-Type: application/json" -d '{}'

Confirmed by docs.spring.io

Did this fix it?

Cause 4 of 4

The token was cleared by login or logout and the client kept the old one

1Check

Compare the XSRF-TOKEN cookie before and after the login response. Spring Security clears the stored token on authentication success and logout success.

curl -i -c jar.txt -b jar.txt -X POST http://localhost:8080/login -d 'username=u&password=p'

2Fix

Ask for a fresh token after login and logout. A small /csrf endpoint that returns the CsrfToken lets the client fetch one on demand.

@RestController
public class CsrfController {
    @GetMapping("/csrf")
    public CsrfToken csrf(CsrfToken csrfToken) {
        return csrfToken;
    }
}

3Verify

Log in, call /csrf, and use the returned token on the next POST.

curl -s -b jar.txt http://localhost:8080/csrf

Confirmed by docs.spring.io

Did this fix it?

How do I stop it coming back?

  • Decide per application whether it is browser-facing or a pure token API, and configure CSRF once to match.
  • Render forms with Thymeleaf or the Spring form tags so the hidden token field is never forgotten.
  • Keep the Spring Security test helper csrf() in MockMvc tests so a missing token shows up in CI.
  • Fetch a fresh token after login and logout in single-page apps.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.