Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

What is a CSRF attack, how does Spring Security's CSRF protection work by default, and when is it reasonable to disable it?

CSRF (cross-site request forgery) tricks a logged-in user's browser into sending a request to our site, and the browser attaches the user's cookies automatically. Spring Security blocks this by default: every POST, PUT, PATCH and DELETE must carry a CSRF token that the attacker's page cannot read, and since 6.0 that token is loaded lazily and masked per request to resist BREACH. Disabling it is reasonable for APIs authenticated only by bearer tokens in a header, never for cookie-authenticated endpoints, and SameSite cookies reduce the risk but do not replace the token.

Why this question is asked

CSRF is one of those attacks that sounds old-fashioned until we see how little it needs: a logged-in user and a page they visit. It is also the first thing many developers turn off in Spring Security, usually because a POST returned 403 and csrf().disable() made it go away. Interviewers ask this to find out whether we know why the protection exists and when turning it off is actually safe. In this answer, we will see how the attack works, how Spring Security's default protection stops it, what changed in Spring Security 6, when disabling it is justified, and where SameSite cookies fit.

1How a CSRF Attack Works

When a user logs in to a site with a session cookie, the browser stores that cookie and sends it with every request to the site, no matter which page started the request. That is convenient, and it is the whole basis of the attack. An attacker builds a page on their own domain with a hidden form that posts to our site, and gets the user to visit it while they are logged in.

XML
<!-- on https://evil.example -->
<form action="https://bank.example.com/transfer" method="POST" id="f">
<input type="hidden" name="to" value="attacker-account">
<input type="hidden" name="amount" value="5000">
</form>
<script>document.getElementById("f").submit();</script>
<!-- the browser sends: POST /transfer with Cookie: SESSION=... (the victim's session) -->
Step throughA forged request rides on the victim's cookie
Victim browserevil.examplebank.example.com
Log in, receive SESSION cookie
Visit attacker page
Hidden form + auto-submit
POST /transfer + SESSION cookie
Valid session: transfer done
Response (attacker cannot read it)

6 messages in order. Play them, or step through them one at a time.

Notice that the attacker never sees the cookie. They do not need to: the browser attaches it for them, and the bank sees a valid session asking for a transfer. The attacker also cannot read the response, because the same-origin policy stops a page on evil.example from reading responses from bank.example.com. So CSRF is about making the user's browser perform actions, not about stealing data.

2How Spring Security Stops It

Spring Security's CsrfFilter is on by default. For requests that change state, POST, PUT, PATCH and DELETE, it requires a CSRF token: a random value tied to the user's session, sent either as a form parameter named _csrf or in a header such as X-CSRF-TOKEN. Safe methods like GET, HEAD, OPTIONS and TRACE are not checked, which is one reason GET requests must never change state.

The defence works because the attacker's page cannot obtain the token. It is stored on the server (by default in the HTTP session) and rendered into our own pages, and the same-origin policy prevents evil.example from reading those pages. A forged form can carry the cookie but not the token, so the request gets 403.

XML
<!-- Thymeleaf with Spring Security adds the token to forms automatically -->
<form th:action="@{/transfer}" method="post">
<input name="to"> <input name="amount">
</form>
<!-- rendered: <input type="hidden" name="_csrf" value="b3d1...masked..."> -->
// POST /transfer with SESSION cookie and _csrf -> 200
// POST /transfer with SESSION cookie, no _csrf -> 403

Server-rendered applications get this almost for free: Thymeleaf, JSP form tags and FreeMarker integrations insert the hidden field. JavaScript clients read the token from a meta tag or cookie and send it in a header.

3What Changed in Spring Security 6

Two details changed in 6.0. First, the token is loaded lazily, as a deferred token: Spring Security no longer reads or creates it on every request, only when something actually needs it, such as a form rendering it or a state-changing request being checked. That avoids touching the session on every request, which helps performance and stateless pages.

Second, the default request handler, XorCsrfTokenRequestAttributeHandler, masks the token: each time it is rendered, the real token is combined with fresh random bytes using XOR, so the value in the page differs on every response while the server can still recover the real token. This protects against BREACH, an attack that guesses secrets in compressed HTTPS responses by watching their size; a value that changes each time cannot be guessed that way. Most applications notice nothing, but single-page apps that copy a raw cookie value into a header can break, and need the SPA configuration from the reference documentation.

4When It Is Reasonable to Disable CSRF

CSRF depends on the browser attaching credentials automatically. Cookies and HTTP Basic credentials remembered by the browser are attached automatically; an Authorization: Bearer header is not. A page on evil.example cannot make the user's browser add our bearer token to a request, because the token lives in our application's JavaScript memory or on a server, not in the browser's cookie jar.

So for an API that authenticates only with bearer tokens in a header, and ignores cookies entirely, CSRF protection adds nothing and can be disabled for that filter chain. The important word is only: if the same endpoints also accept a session cookie, for example because a browser app shares them, CSRF protection must stay.

Java
@Bean @Order(1)
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.securityMatcher("/api/**")
.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) // bearer tokens only
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(csrf -> csrf.disable()); // safe: no cookies used
return http.build();
}
// the web chain for pages and forms keeps the default CSRF protection
Step throughCan this chain disable CSRF?
  1. Does any endpoint accept cookies?Session, remember-me, BFF cookie
    YesKeep CSRF onNoNext question
  2. Browser-remembered Basic auth?Browsers resend it automatically
    YesKeep CSRF onNoNext question
  3. Only Authorization: Bearer?Token not in the cookie jar
    YesCSRF can be disabledNoKeep CSRF on

3 steps in order. Play them, or step through them one at a time.

5SameSite Cookies Help but Do Not Replace Tokens

The SameSite attribute tells the browser when to send a cookie on cross-site requests. With SameSite=Strict it is never sent cross-site; with Lax it is sent only on top-level navigations with safe methods such as clicking a link, so a cross-site POST form does not carry it. Modern browsers treat cookies without the attribute as Lax by default, which has already removed many classic CSRF attacks.

But it is not a full replacement. Lax still allows GET navigations, so any GET that changes state is exposed. Sibling subdomains count as the same site, so a compromised or user-controlled subdomain can still forge requests. Older browsers and some embedded web views behave differently. So we use SameSite as a second layer and keep the CSRF token as the main defence.

6Follow-up questions

Why does my POST from Postman get 403 when the browser works?

Because Postman is not sending the CSRF token. The browser form includes the hidden _csrf field that Thymeleaf rendered; Postman does not. For testing, read the token from a page or use Spring Security's test support, such as with(csrf()) in MockMvc.

Is CSRF possible with JSON APIs that use cookies?

Yes. A plain HTML form cannot send application/json, but some endpoints also accept form-encoded bodies, and misconfigured CORS can allow cross-site JSON requests with credentials. If an API is authenticated with cookies, keep CSRF protection on.

Does HTTPS prevent CSRF?

No. HTTPS protects the request in transit, but the forged request is a perfectly valid HTTPS request sent by the user's own browser with their cookie.

7Conclusion

In this answer, we saw that CSRF makes a logged-in user's browser send a forged request that carries their cookies. Spring Security stops it by default by requiring a token on state-changing methods that the attacker's page cannot read, and since 6.0 the token is loaded lazily and masked per request against BREACH. Disabling CSRF is reasonable only for chains authenticated purely by bearer tokens in headers, and SameSite cookies are a useful second layer rather than a replacement.

What to say in the interviewAbout 90 seconds aloud

Open with

CSRF, cross-site request forgery, is when an attacker's page makes a logged-in user's browser send a request to our site. The browser attaches the session cookie automatically, so the request looks legitimate, for example a hidden form that posts a transfer.

Then, if they want more

The attacker cannot read the response, but the action happens. Spring Security protects against it by default. For state-changing methods, POST, PUT, PATCH and DELETE, the CsrfFilter requires a token that is tied to the session and rendered into our own pages, as a hidden _csrf field or sent in a header.

The attacker's page cannot read our pages because of the same-origin policy, so it cannot include the token and gets a 403. Since Spring Security 6 the token is deferred, so it is only loaded when needed, and by default it is masked with XOR on every response, which protects against BREACH-style compression attacks.

That masking is why some single-page apps broke after upgrading. Disabling CSRF is reasonable when a filter chain authenticates only with bearer tokens in the Authorization header and never uses cookies, because the browser does not add that header automatically. If any endpoint in the chain accepts a cookie, it stays on.

SameSite cookies, especially Lax, block many attacks, but they still allow GET navigations and treat sibling subdomains as the same site, so I treat them as an extra layer, not a replacement.

About this answer

Last updated
12 November 2026
Versions it names
Spring Security 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
OWASP Top Ten
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is a CSRF attack, how does Spring Security's CSRF protection work by default, and...": https://scrivio-interview-library.netlify.app/spring-boot/web-security-threats/a4501c335c/