CSRF: when it matters

Spring Security · lesson 10 of 31 · 3 min read

Decide correctly whether to keep CSRF protection on, and wire the token for forms and SPAs.

Open this lesson in the learning hub

Key points

  • CSRF abuses ambient credentials. If the browser attaches a cookie automatically, another site can fire a request as you.
  • Cookie or session based login -> keep CSRF on. It is enabled by default and it is protecting real users.
  • Token in an Authorization header? The browser never adds it for you, so there is nothing to forge. Disabling CSRF is right.
  • Thymeleaf form posts include the hidden token automatically. Hand-written forms and fetch() calls must send it themselves.
  • Session-based SPA? Use CookieCsrfTokenRepository.withHttpOnlyFalse() and echo the cookie back as X-XSRF-TOKEN.
  • Spring Security 6 masks the token (BREACH defence). SPAs reading the cookie need CsrfTokenRequestAttributeHandler.

Example

// Bearer-token API: no cookies, no CSRF surface
http.csrf(csrf -> csrf.disable());

// Session-based SPA: readable cookie, header echoed back
CsrfTokenRequestAttributeHandler handler = new CsrfTokenRequestAttributeHandler();
handler.setCsrfRequestAttributeName(null);   // opt out of deferred token loading

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

Cookies in play? Keep CSRF. Bearer tokens only? Turning it off is not a shortcut, it is correct.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Security course, and every lesson in it is listed on the Spring Security contents page.