Have you ever configured Spring Security and suddenly found your POST requests returning 403? Many developers check the logs, can’t figure out the cause, and end up just writing csrf().disable().
Whether that setting is correct depends entirely on what kind of application you’re building. For a REST API, disabling it is fine. For a Thymeleaf form-based application, you need to keep it enabled, or you leave a real security hole. This article explains when each setting is the right choice and why.
First, some background. Spring Security’s CSRF protection is handled by CsrfFilter and is enabled by default. It checks requests that change state, such as POST, PUT, PATCH and DELETE. GET, HEAD, TRACE and OPTIONS requests pass through without a token. That’s why you see the classic symptom of GET requests working while only POST requests return 403.
How CSRF Attacks Work
CSRF stands for Cross-Site Request Forgery. It’s an attack that tricks a logged-in user into performing an action they never intended.
A concrete scenario makes this easier to understand. Suppose you’re logged in to your bank’s website (bank.example.com) and you open a different, malicious site (evil.example.com). That site contains the following hidden HTML:
<form action="https://bank.example.com/transfer" method="POST">
<input type="hidden" name="to" value="attacker-account">
<input type="hidden" name="amount" value="100000">
</form>
<script>document.forms[0].submit();</script>
As soon as the page loads, the form submits automatically. At that moment, the browser automatically attaches the session cookie for bank.example.com. To the bank’s server, the transfer looks like a request from the real user. The root cause is browser behavior: the browser automatically sends the cookies that belong to the destination domain.
Why REST APIs (JWT Authentication) Don’t Need CSRF Protection
For a stateless REST API that uses JWT, you can safely disable CSRF protection. There are three reasons.
JWTs are sent in the Authorization header. Browsers don’t attach custom headers automatically, so a form on a malicious site has no way to send the token.
CORS preflight requests block custom headers. When a request includes an Authorization header, the browser first sends an OPTIONS request. If CORS is configured correctly, requests from other domains stop there.
Stateless APIs don’t use sessions. CSRF depends on a session cookie being sent automatically. Without a session, the conditions for the attack don’t exist.
For details on implementing JWT, see this article.
Session and Cookie-Based Form Apps Need CSRF Protection
Server-side rendered applications such as Thymeleaf apps usually keep the session ID in a cookie. That setup meets every condition a CSRF attack needs.
Once a session cookie is issued after login, the browser automatically attaches it to every request to that domain. Even when a <form> on a malicious site submits the request, the browser still attaches the session cookie, so the server can’t tell it apart from a legitimate request.
CSRF tokens solve this problem. The server embeds a random token in each form and rejects any request whose token doesn’t match, which blocks requests coming from malicious sites.
Diagnosing 403 Errors
Quick Reference: Causes and Fixes by Symptom
| Symptom | Likely Cause | Fix |
|---|---|---|
| GET works, but POST/PUT/DELETE returns 403 | No CSRF token is being sent | Embed _csrf in the form, or disable CSRF if you use JWT authentication |
InvalidCsrfTokenException in the logs | A stale token is cached | Clear browser cookies and the session, then log in again |
MissingCsrfTokenException in the logs | The request doesn’t include a token | For AJAX, add the X-CSRF-TOKEN header |
| 403 even for same-origin requests | Spring Security filter order or path exclusion settings | Check the matcher order in authorizeHttpRequests |
| Preflight OPTIONS request fails | Missing CORS configuration (not a CSRF issue) | Check your CorsConfigurationSource |
If the table doesn’t help you find the cause, enable logging.level.org.springframework.security=TRACE and look at the log output around CsrfFilter.
Start by checking your application logs. If you see InvalidCsrfTokenException or MissingCsrfTokenException, CSRF is the cause.
The typical CSRF symptom is that GET works, but only POST/PUT/DELETE return 403. To see more detailed logs, set the log level to TRACE:
# application.properties
logging.level.org.springframework.security=TRACE
CORS errors are easy to confuse with CSRF errors, but they’re a separate issue. CORS is the mechanism by which the browser blocks requests to other origins. See this guide to CORS configuration.
Spring Security 6: Disabling CSRF for REST APIs
For a REST API that uses JWT authentication, use the following configuration:
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// JWT認証のためセッション不使用・CSRF不要
.csrf(csrf -> csrf.disable())
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
);
return http.build();
}
Spring Security 5 and earlier used http.csrf().disable(). Spring Security 6 uses the Lambda DSL instead. Add a comment explaining why CSRF is disabled so anyone reading the configuration later understands the intent. Pairing it with SessionCreationPolicy.STATELESS also states in code that the application doesn’t create sessions.
Spring Security 6: Enabling CSRF for Thymeleaf Form Apps
CSRF protection is enabled by default in Spring Security. Use withDefaults() to state that intent explicitly in your code:
import static org.springframework.security.config.Customizer.withDefaults;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(withDefaults()) // セッション認証のため有効化(デフォルト動作を明示)
.formLogin(withDefaults())
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
);
return http.build();
}
When you use th:action in Thymeleaf, a hidden _csrf field is embedded automatically.
<!-- Thymeleafテンプレート -->
<form th:action="@{/profile/update}" method="post">
<input type="text" name="username" />
<button type="submit">更新</button>
</form>
If you inspect the generated HTML in your browser’s developer tools, you can see the inserted hidden field:
<!-- 実際に出力されるHTML -->
<form action="/profile/update" method="post">
<input type="hidden" name="_csrf" value="abc123...">
<input type="text" name="username" />
<button type="submit">更新</button>
</form>
Plain HTML forms that don’t use Thymeleaf don’t get this automatic embedding, so you have to add the token yourself. For more on Thymeleaf, see this guide to using Thymeleaf.
Choosing a CsrfTokenRepository: HttpSessionCsrfTokenRepository vs. CookieCsrfTokenRepository
CsrfTokenRepository is the interface that decides where CSRF tokens are stored and how they’re validated. If you don’t configure one, Spring Security uses HttpSessionCsrfTokenRepository. If JavaScript needs to read the token from a cookie, switch to CookieCsrfTokenRepository.
| Item | HttpSessionCsrfTokenRepository (default) | CookieCsrfTokenRepository |
|---|---|---|
| Token storage | Server-side HttpSession | XSRF-TOKEN cookie |
| Expected header | X-CSRF-TOKEN | X-XSRF-TOKEN |
| Form parameter name | _csrf | _csrf |
| Best suited for | Form-based apps such as Thymeleaf apps | Apps that send AJAX requests from axios or Angular |
If the server renders your pages and can embed the token in the HTML, the default is all you need. Choose CookieCsrfTokenRepository only when JavaScript has to read the token itself.
If you need the cookie or header name to match your frontend’s conventions, create an instance and then change its settings:
CookieCsrfTokenRepository repository = CookieCsrfTokenRepository.withHttpOnlyFalse();
repository.setCookieName("MY-XSRF-TOKEN");
repository.setHeaderName("X-MY-XSRF-TOKEN");
repository.setCookiePath("/");
repository.setCookieCustomizer(cookie -> cookie.sameSite("Strict"));
http.csrf(csrf -> csrf.csrfTokenRepository(repository));
The cookie doesn’t get a SameSite attribute by default. If you need one, set it with setCookieCustomizer (Spring Security 6.1 and later).
Sending CSRF Tokens with AJAX Requests
When a form-based app uses AJAX, you need to add the CSRF token to a request header. The standard approach is to embed the token in meta tags and read it with JavaScript:
<meta name="_csrf" th:content="${_csrf.token}">
<meta name="_csrf_header" th:content="${_csrf.headerName}">
const token = document.querySelector('meta[name="_csrf"]').content;
const header = document.querySelector('meta[name="_csrf_header"]').content;
fetch('/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
[header]: token
},
body: JSON.stringify({ key: 'value' })
});
How CookieCsrfTokenRepository.withHttpOnlyFalse() Works
If you want fetch or axios to read the token from a cookie automatically, use CookieCsrfTokenRepository:
http
.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
);
withHttpOnlyFalse() issues the token as an XSRF-TOKEN cookie without the HttpOnly flag. JavaScript reads it from document.cookie and sends it back in the X-XSRF-TOKEN header, and CsrfFilter compares the header value with the cookie value.
Angular supports this pattern out of the box, because HttpClientXsrfModule automatically copies the XSRF-TOKEN cookie into the X-XSRF-TOKEN header. With axios, you get the same behavior by setting withCredentials: true, xsrfCookieName: 'XSRF-TOKEN' and xsrfHeaderName: 'X-XSRF-TOKEN'.
If you choose withHttpOnlyFalse(), you need stronger XSS protection. A successful XSS attack would let JavaScript read the token, so set a Content-Security-Policy header and escape all user input consistently.
When Sending the Cookie Token Still Returns 403 in Spring Security 6
Spring Security 6 changed how tokens are handled in two ways. First, XorCsrfTokenRequestAttributeHandler is now the default as a defense against BREACH attacks, so the server expects the token it receives to be masked. A SPA that copies the raw cookie value straight into X-XSRF-TOKEN fails validation and gets a 403.
Second, tokens are now loaded lazily. If the page never accesses the token, the XSRF-TOKEN cookie may never be issued.
If your setup sends the cookie value as-is, switch the request handler back to CsrfTokenRequestAttributeHandler:
http.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler())
);
This configuration removes the BREACH masking, so use it only if you accept that trade-off. To fix the missing cookie, add a OncePerRequestFilter that simply calls CsrfToken#getToken(), which forces the token to load on every request. The SPA configuration in the official reference follows the same approach.
How SameSite Cookies Help Mitigate CSRF
The SameSite attribute is a browser feature that controls whether a cookie is sent with cross-site requests, and it helps mitigate CSRF attacks. Here’s how its three values behave:
| Value | Same-site navigation | Cross-site GET (link clicks, etc.) | Cross-site POST (attack scenario) | CSRF mitigation |
|---|---|---|---|---|
Strict | Sent | Not sent | Not sent | Strongest (users may not stay logged in when they arrive from an external link) |
Lax | Sent | Sent | Not sent | Practical balance (default in modern browsers) |
None | Sent | Sent | Sent | No mitigation (Secure required) |
To set SameSite explicitly in Spring Boot, add the following to application.properties:
server.servlet.session.cookie.same-site=lax
server.servlet.session.cookie.secure=true
server.servlet.session.cookie.http-only=true
The resulting Set-Cookie response header looks like this:
Set-Cookie: JSESSIONID=ABC123; Path=/; Secure; HttpOnly; SameSite=Lax
Chrome 80 and later, along with recent versions of Firefox and Safari, treat cookies without a SameSite attribute as Lax, which makes CSRF attacks harder than they used to be. However, SameSite alone is not enough protection in these cases:
- You need to support older browsers (Chrome 79 and earlier, IE11, etc.)
- Attacks between subdomains (
SameSitetreats everything under the same eTLD+1 as the same site, so it may not stop an attack fromevil.example.comagainstbank.example.com) Laxblocks POST requests but doesn’t block GET requests with side effects (which you should avoid by design anyway)
So treat SameSite as one layer of defense in depth, not as a replacement for CSRF tokens, and use it together with Spring Security’s token validation.
Summary
The right configuration depends on the type of application:
| Case | Configuration |
|---|---|
| REST API + JWT/API key | csrf(csrf -> csrf.disable()) + STATELESS |
| Thymeleaf forms + session | csrf(withDefaults()) + automatic token embedding |
| Form app + AJAX | CookieCsrfTokenRepository.withHttpOnlyFalse() |
| Mixed REST API and forms | Use requestMatcher to apply different settings by path |
Writing csrf().disable() in a session-based form app creates a real security hole. When you hit a 403 error, find the cause in the logs first, then choose the configuration that fits your application.
For more security tips: to protect sensitive values in configuration files, see How to Encrypt Sensitive Configuration Values in Spring Boot with Jasypt. To handle exceptions other than 403 in a production-ready way, see Implementing a Production-Ready GlobalExceptionHandler in Spring Boot.