Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 39 ยท CSRF, CORS and Headers

CSRF Protection in Spring Security

Understand cross-site request forgery and how Spring Security stops it: synchronizer tokens, SameSite cookies, SPA setups, BREACH masking and when to disable CSRF.

Imagine you are logged in to bank.example. In another tab you open a page that silently submits a hidden form to https://bank.example/transfer. Your browser dutifully attaches the bank's session cookie, and the bank sees a normal, authenticated request. That is cross-site request forgery (CSRF): the attacker cannot read your data, but can make your browser perform actions.

Spring Security enables CSRF protection by default for browser-style requests that change state (POST, PUT, PATCH, DELETE). This lesson explains how it works and how to configure it. The real framework classes cannot run on this site, so the runnable examples are plain Java stand-ins for the token logic.

The synchronizer token pattern

The defence relies on one fact: a page on another origin cannot read your page's content, so it cannot learn a secret that is embedded in it.

  1. When the server renders a form it includes a random CSRF token (also stored server-side in the session).
  2. On every state-changing request the client must send the token back, as a hidden form field _csrf or the header X-CSRF-TOKEN.
  3. The server compares the received token with the stored one. A forged request has the cookie but not the token, so it is rejected with 403.

The forged request

evil.example Hidden form to the bank
Browser adds cookie Automatically
Bank sees a valid session
1 / 2
Java Synchronizer token store (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two design rules follow: never change state with GET (it is not protected), and keep the token out of URLs and logs.

Using the token in Spring

With Thymeleaf, forms get the hidden field automatically. With plain HTML or a JavaScript client you read the token from the request:

HTML
<form method="post" action="/transfer">
  <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
  <button>Send</button>
</form>

For fetch calls from a page you can put the values in <meta> tags and send the header:

HTML
<meta name="_csrf" th:content="${_csrf.token}">
<meta name="_csrf_header" th:content="${_csrf.headerName}">

A SPA cannot easily receive a server-rendered token. Spring can store it in a readable cookie called XSRF-TOKEN; Angular and Axios automatically copy it into the X-XSRF-TOKEN header:

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

The cookie must be readable by JavaScript (HttpOnly=false) for this to work. That is safe: the session cookie stays HttpOnly, and an attacker's site still cannot read another origin's cookies. This is the double-submit cookie variation: the server compares the cookie value with the header value.

Since Spring Security 6, tokens are also masked per request to defeat the BREACH compression attack: the real token is XORed with a fresh random value and the pair is sent. The server unmasks it before comparing.

Java Token masking against BREACH (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Every response contains a different-looking token even though the secret is the same, so an attacker who watches response sizes cannot reconstruct it byte by byte.

SameSite cookies as a second layer

Modern browsers treat cookies without an explicit setting as SameSite=Lax: they are not sent on cross-site POSTs. Setting SameSite=Lax or Strict on the session cookie (server.servlet.session.cookie.same-site=lax) blocks most CSRF on its own. Keep CSRF tokens as well: SameSite is "same site", not "same origin", and older browsers differ.

When can you disable CSRF?

Java
http.csrf(csrf -> csrf.disable());

Only when the API authenticates with something the browser does not attach automatically, typically a bearer token in the Authorization header (see Resource server configuration) and no session cookie. If any endpoint trusts a cookie or HTTP Basic credentials cached by the browser, keep CSRF on. To ignore it for a few paths, such as a webhook protected by a signature, use csrf.ignoringRequestMatchers("/webhooks/**").

A 403 on every POST right after adding Spring Security is almost always a missing CSRF token, not a permissions problem. Check the browser's request: is _csrf or X-CSRF-TOKEN present?

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can an attacker's site not complete a CSRF-protected POST?

    The browser attaches the cookie, but the same-origin policy stops the other site from reading the token in the page.
  2. 2. Which HTTP methods does Spring's CSRF protection skip by default?

    Those methods are considered safe, which is why state changes must never use GET.
  3. 3. When is it reasonable to disable CSRF?

    CSRF abuses automatically attached credentials. A header-based token is not attached automatically.
  4. 4. What problem does per-request token masking address?

    Masking makes every response carry a different-looking token so compression sizes leak nothing.

Summary

  • CSRF makes the victim's browser send authenticated requests; a secret token that other origins cannot read stops it.
  • Spring enables it by default for non-safe methods; forms carry _csrf, scripts send X-CSRF-TOKEN.
  • SPAs can use CookieCsrfTokenRepository.withHttpOnlyFalse().
  • Add SameSite cookies as defence in depth.
  • Disable CSRF only for stateless, header-authenticated APIs.

Next: CORS configuration