Spring Security cannot verify the CSRF token because the session is gone
403 Forbidden after the page has been open for a whileShort answer
By default Spring Security keeps the expected CSRF token in the HTTP session. If the session expired, was never created or sits on another node, there is nothing to compare against and the request is denied. Keep the token in a cookie, share the session, or handle the denial with a custom handler.
Fix it fast
1Find out which cause you have
Check whether the failing request carries a session cookie, and whether the server still knows that session. Compare the session timeout with how long the page was idle.
grep -rn "session.timeout" src/main/resources/ curl -i -b "JSESSIONID=<value from the browser>" http://localhost:8080/api/ping2Match what you see, then jump to its fix
- 1
The first submit after a long idle period fails, a reload then worksThe HTTP session expired while the form was openFix - 2
Users see the error page after the session endsYou want a friendly page instead of a bare 403Fix - 3
Failures appear only behind a load balancer, or after a restart or deployThe expected token is read from the session on a different nodeFix
- 1
What does the error look like?
403 Forbidden after the page has been open for a whileInvalidCsrfTokenException
Cause 1 of 3
The HTTP session expired while the form was open
1Check
Compare the idle time with server.servlet.session.timeout. The session holds the expected token, so when it ends the token goes with it.
grep -rn "server.servlet.session.timeout" src/main/resources/2Fix
Store the token in a cookie instead of the session, so it does not depend on the session lifetime.
http.csrf(csrf -> csrf
.csrfTokenRepository(new CookieCsrfTokenRepository()));3Verify
Restart, leave a form open past the session timeout, then submit.
curl -i -c jar.txt http://localhost:8080/login | grep -i xsrfConfirmed by docs.spring.io
Cause 2 of 3
You want a friendly page instead of a bare 403
1Check
The CsrfFilter hands the failure to the AccessDeniedHandler. The handler decides what the user sees, so a bare 403 means no handler of yours is in place.
grep -rn "accessDenied\|exceptionHandling" src/main/java2Fix
Register an access denied page or a custom AccessDeniedHandler that treats InvalidCsrfTokenException as 'session expired, please sign in again'.
http.exceptionHandling(ex -> ex.accessDeniedPage("/access-denied"));3Verify
Trigger the failure and confirm /access-denied is shown.
curl -i -X POST http://localhost:8080/ordersConfirmed by docs.spring.io
Cause 3 of 3
The expected token is read from the session on a different node
1Check
The token repository reads the token from a session, whether it is in memory, a cache or a database. If requests land on a node that does not have that session, no token is found.
curl -i -c jar.txt http://app.example.com/login && curl -i -b jar.txt http://app.example.com/login2Fix
Use the cookie token repository (above) so the token no longer depends on which node holds the session.
http.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()));3Verify
Send several requests through the load balancer with one cookie jar and confirm none returns 403.
for i in 1 2 3 4 5; do curl -s -o /dev/null -w "%{http_code}\n" -b jar.txt http://app.example.com/; doneConfirmed by docs.spring.io
How do I stop it coming back?
- Pick the token repository on purpose: session for plain server-rendered apps, cookie for apps that run on several nodes.
- Show a clear 'session expired' page rather than a bare 403.
- Keep the session timeout longer than the time users take to fill your longest form.
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
Security
POST requests return 403 in Spring Security because the CSRF token is missing
MissingCsrfTokenException
Spring Security checks a CSRF token on every request except GET, HEAD, TRACE and OPTIONS.
4 causes, each with a fixSecurity
Jwts.parserBuilder() no longer compiles after upgrading JJWT
setSigningKey / parseClaimsJws / getBody shown as deprecated
JJWT 0.12.0 removed Jwts.parserBuilder() because Jwts.parser() now returns the builder itself.
3 causes, each with a fixSecurity
Spring Boot cannot find a ClientRegistrationRepository bean for OAuth2 login
APPLICATION FAILED TO START
Boot creates the ClientRegistrationRepository from spring.security.oauth2.client.registration properties.
3 causes, each with a fixSecurity
Spring Security fails to resolve the issuer configuration for a JWT or Keycloak
The identity server is up but the Spring app fails on the first token
Spring Security fetches the issuer's discovery document before it can validate tokens.
3 causes, each with a fixSecurity
Changing the error response when a JWT is rejected in Spring Security
403 Forbidden for a valid token that lacks the required authority
A resource server answers a bad token with 401 and a WWW-Authenticate header, and a valid token without enough rights with 403.
2 causes, each with a fixSecurity
A Microsoft Entra access token shows Invalid Signature when you check it yourself
Tokens that a Microsoft API receives might not always be a JWT that can be decoded
A token issued for Microsoft Graph is not meant for you to validate, so a failed signature check is expected.
2 causes, each with a fix