Sub topic 8
CSRF: when to keep it and when to disable it
This chapter assumes you can write a Spring Boot REST controller, read a SecurityFilterChain bean, and know how HTTP methods, status codes, and cookies work. You should also know the difference between stateless and session-based authentication from the previous chapters.
What CSRF is
Cross-site request forgery (CSRF) is an attack where a malicious site makes a user's browser send a request to another site where the user is already logged in. The browser attaches the user's cookies automatically, so the target server sees a request that looks genuine.
The attack depends on one browser behavior: credentials that the browser sends without the page's code asking it to. Session cookies and HTTP Basic credentials that the browser has cached both work this way.
How Spring Security defends
Spring Security enables CSRF protection by default. For every request that can change state (POST, PUT, PATCH, DELETE), it requires a token that an attacker's page cannot read. Safe methods (GET, HEAD, OPTIONS, TRACE) are not checked.
If you use server-rendered pages or a single-page app that authenticates with a session cookie, keep this protection on. A common setup for a JavaScript client stores the token in a cookie that the script 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.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
@Configuration
public class CsrfConfig {
@Bean
SecurityFilterChain sessionApi(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.formLogin(Customizer.withDefaults());
return http.build();
}
}The client reads the XSRF-TOKEN cookie and sends its value back in the X-XSRF-TOKEN header on each unsafe request. An attacker's page on another origin cannot read that cookie, so it cannot build a valid request.
When you can disable it
The CSRF attack needs the browser to add credentials on its own. If your API authenticates every request with something the browser does not add automatically, the attack has nothing to use. The usual case is a bearer token in the Authorization header, such as a JWT, sent by code you control.
Disable CSRF only when all of these hold:
- The API is stateless and creates no session.
- Clients send credentials explicitly in a header on each request.
- No cookie is used to authenticate requests.
http
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));Common mistakes
| Mistake | Why it matters |
|---|---|
| Disabling CSRF "to make POST work" on a cookie-session app | Removes the only defense against forged requests. Fix the client to send the token instead. |
| Disabling CSRF while using HTTP Basic in a browser | Browsers cache Basic credentials and resend them, so forged requests can succeed. |
| Storing a JWT in a cookie that the API reads as authentication | The browser now adds the credential automatically, which brings the CSRF risk back. |
| Seeing 403 on POST and assuming authorization is wrong | A missing CSRF token also gives 403. Check the token first. |
The Basic row deserves care. The example SecurityFilterChain from the earlier chapter combines csrf.disable() with httpBasic. That is acceptable for a service called by scripts or other servers. If a browser user can log in through the Basic prompt, treat the API as cookie-like and keep CSRF on.
Quick decision guide
- Does the API use a session cookie to identify the user? Keep CSRF on.
- Do browsers use HTTP Basic against it? Keep CSRF on.
- Is it stateless, with bearer tokens that your client code adds to each request? You may disable CSRF.
Exercise
Your team builds a stateless API secured with JWT bearer tokens that a single-page app sends in the Authorization header. A colleague proposes also storing the JWT in a cookie and having the API accept it from there, while keeping CSRF disabled. What is the problem?
Show answer
Once the API accepts the cookie as authentication, the browser attaches the credential automatically on cross-site requests. That is exactly what CSRF exploits, and with CSRF disabled nothing stops forged requests. Either keep reading the token only from the Authorization header, or enable CSRF protection for the cookie-based path.