Sub topic 8
CSRF: when to keep it and when to disable it
This chapter assumes you can write a Spring Boot REST controller and read a SecurityFilterChain bean. You should know HTTP methods, cookies, and the Authorization header. By the end you will be able to decide whether a given API needs CSRF protection, and you will know how to configure it either way.
What a CSRF attack is
Cross-Site Request Forgery (CSRF) tricks a user's browser into sending a request to a site where the user is already logged in. The attack works because browsers attach cookies to requests automatically, based on the destination of the request and not on the page that triggered it.
Here is a concrete case. A user logs in to https://bank.example.com, and the server sets a session cookie. In another tab, the user opens https://evil.example.net. That page contains a hidden form that posts to https://bank.example.com/transfer. The browser attaches the bank's session cookie, and the bank sees what looks like a normal, authenticated request.
The attacker never sees the cookie and never reads the response. The attack only needs the browser to send a request that changes state. That is why CSRF targets unsafe methods such as POST, PUT, PATCH and DELETE.
The condition that makes CSRF possible
CSRF needs two things at once:
- The server authenticates requests using a credential the browser sends automatically. Session cookies are the usual example. HTTP Basic credentials that the browser has cached for a site behave the same way.
- The request changes state, and an attacker can cause the browser to send it.
If the credential is something the browser does not attach on its own, the attack has nothing to ride on. A JWT sent in the Authorization: Bearer ... header is the standard case. JavaScript on your own page has to read the token and set the header. A form on evil.example.net cannot do that, and it cannot read your token from another origin.
What Spring Security does by default
Spring Security enables CSRF protection by default for unsafe methods. The safe methods GET, HEAD, OPTIONS and TRACE are not checked. For each unsafe request, the CsrfFilter compares a token supplied by the client with the expected token held by the server. If the token is missing or wrong, the request is rejected with 403.
The token is not a login credential. It is a value the attacker's page cannot know, so a forged request lacks it.
Spring Security 6 uses a deferred token and a CsrfTokenRequestHandler. The token is only loaded when something needs it, which avoids creating a session for requests that never use it.
You can see the default behavior with a form-based app. A POST without a token fails:
curl -i -u alice:change-me -X POST http://localhost:8080/api/orders \
-H "Content-Type: application/json" -d '{"item":"book"}'The response is 403 Forbidden, even though the credentials are valid. This surprises many people the first time they build a REST API with Basic auth. The credentials passed authentication, and the CSRF check then failed.
Deciding: keep it or disable it
Use the way your API authenticates clients as the deciding factor.
| How clients authenticate | Browser sends credential automatically? | CSRF protection |
|---|---|---|
| Session cookie (`JSESSIONID` or similar) | Yes | Keep it |
| Cookie containing a JWT | Yes | Keep it |
| `Authorization: Bearer` header with JWT | No | Can disable |
| HTTP Basic from non-browser clients only | No (the client sets it) | Can disable |
| HTTP Basic used from a browser prompt | Yes, cached by the browser | Keep it |
The rule is not "REST means no CSRF". The rule is "no automatically attached credentials means no CSRF risk". An API that stores its token in a cookie is exposed, even though it is a REST API.
Disabling CSRF for a stateless API
For an API that uses bearer tokens or non-browser Basic clients and keeps no session, disable CSRF explicitly. This matches the chain from the earlier chapter on defining a SecurityFilterChain.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class StatelessApiConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}Both lines matter together. STATELESS means Spring Security never creates or uses an HttpSession to hold the SecurityContext. Without a session cookie, there is no ambient credential for an attacker to ride on. Disabling CSRF while still allowing sessions is the risky combination.
Keeping CSRF for cookie-based clients
If a browser app logs in with a session cookie, keep CSRF on and decide how the front end gets the token. The common choice for a single-page app (SPA) is a cookie that JavaScript can read.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler;
@Configuration
@EnableWebSecurity
public class SpaSecurityConfig {
@Bean
SecurityFilterChain spa(HttpSecurity http) throws Exception {
var handler = new CsrfTokenRequestAttributeHandler();
handler.setCsrfRequestAttributeName(null);
http
.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(handler))
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.formLogin(Customizer.withDefaults());
return http.build();
}
}CookieCsrfTokenRepository.withHttpOnlyFalse() writes the token to a cookie named XSRF-TOKEN that JavaScript can read. The client copies its value into an X-XSRF-TOKEN request header on each unsafe request. An attacker's page on another origin cannot read your cookie, so it cannot build the header.
Setting the request attribute name to null makes the token load eagerly, so the cookie is written on the first response. Without it, the deferred loading in Spring Security 6 means the cookie may not appear until something reads the token. The Spring Security documentation describes this SPA pattern. Check it against your version, because the handler classes changed between 5.x and 6.x.
A browser client sends the header like this:
const token = document.cookie
.split("; ")
.find(c => c.startsWith("XSRF-TOKEN="))
?.split("=")[1];
await fetch("/api/orders", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"X-XSRF-TOKEN": token
},
body: JSON.stringify({ item: "book" })
});Excluding specific paths
Sometimes only a few endpoints need an exemption, such as a webhook called by a third party with its own signature check. Exclude those paths and leave the rest protected, instead of disabling CSRF globally.
http.csrf(csrf -> csrf
.ignoringRequestMatchers("/webhooks/**"));Keep exemptions narrow, and make sure the exempt endpoint authenticates the caller another way, such as verifying an HMAC signature.
Related defenses and their limits
CSRF tokens are not the only layer. They work alongside other controls:
- SameSite cookies. A cookie with
SameSite=LaxorStrictis not sent on most cross-site requests. Modern browsers default toLax. This reduces CSRF risk, but it depends on the browser, and it does not cover same-site subdomain attacks. Treat it as defense in depth, not a replacement. - CORS. CORS controls whether a page on another origin can read a response. It does not stop the browser from sending a simple cross-site form post. A strict CORS policy is not CSRF protection. The CORS chapter covers it.
- Content type checks. Requiring
application/jsonblocks plain HTML forms, but it is fragile and should not be your only control.
Common errors
- Unexpected 403 on POST with valid credentials. CSRF is enabled and no token was sent. Decide which authentication model you have, then either send the token or disable CSRF for a stateless API.
- Disabling CSRF but keeping
formLoginor sessions. The app stays vulnerable. Paircsrf.disable()withSTATELESSand a header-based credential. - Token present but still 403. The header name or cookie name is wrong, the cookie was not written yet, or the session changed after login so the stored token no longer matches. Inspect the request in the browser's network tab.
- Treating CORS as protection. Allowing only one origin in CORS does not stop forged form posts.
- Disabling CSRF in tests only. If tests use
csrf()post-processing inconsistently, they can pass while production returns 403. Test with the same configuration you deploy.
For MockMvc tests against a CSRF-protected chain, use the helper from spring-security-test:
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
mvc.perform(post("/api/orders")
.with(csrf())
.contentType("application/json")
.content("{\"item\":\"book\"}"))
.andExpect(status().isOk());Also write the negative test: the same request without .with(csrf()) should return 403. That test proves the protection is active.
Exercise
A Spring Boot API authenticates with a JWT in the Authorization header, keeps no sessions, and has no cookie-based login. A teammate says CSRF must stay enabled because "it is a security feature". Another says to disable it everywhere. What would you decide, and what two settings should appear together in the filter chain?
Show answer
Disable CSRF. The browser does not attach an Authorization header automatically, so a forged cross-site request has no credential to ride on. Pair csrf.disable() with SessionCreationPolicy.STATELESS so no session cookie exists as an ambient credential. If the API later adds cookie-based sessions or stores the JWT in a cookie, revisit the decision and re-enable CSRF.
Exercise
Your SPA logs in with a session cookie and every POST returns 403. Name the Spring Security component that rejects the request, and describe how the SPA should fix it without disabling protection.
Show answer
The CsrfFilter rejects the request because the CSRF token is missing. Configure CookieCsrfTokenRepository.withHttpOnlyFalse() so the server writes an XSRF-TOKEN cookie, and have the SPA read that cookie and send its value in an X-XSRF-TOKEN header on each unsafe request, using credentials: "include" so the session cookie is sent too.