How to Prevent CSRF in Spring and Jakarta Apps Correctly
Stop cross-site request forgery with Spring Security's CSRF tokens, SameSite cookies and Origin checks, and know when a stateless API can skip the token.

A user is logged in to your bank site. In another tab, a malicious page contains a hidden form that posts to your transfer endpoint. The browser sends the user's session cookie with it, and the server sees a legitimate authenticated request. That is cross-site request forgery. The defense is a secret the attacker's page cannot know. This post shows it for Spring and for plain Jakarta EE. The failure you hit when it is on and a client does not send the token is in 403 on POST.
Why it works
Browsers attach cookies to requests for a site no matter which page triggered the request. The server cannot tell, from the cookie alone, whether the user clicked your form or an attacker's. The attacker cannot read the response (the same-origin policy prevents it) and does not need to: the damage is the action.
Spring Security: on by default
For applications with a browser UI and session cookies, Spring Security generates a token per session and requires it on POST, PUT, PATCH and DELETE:
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.formLogin(Customizer.withDefaults());
return http.build(); // CSRF protection is enabled
}With Thymeleaf, th:action adds a hidden _csrf field. For JavaScript clients that run on the same site, use a cookie the script can read and a header it echoes back:
http.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()));The browser sends the cookie automatically, which an attacker's page also triggers, but only code running on your origin can read the cookie and copy it into the X-XSRF-TOKEN header. A forged cross-site request has the cookie and no matching header, and fails.
When a stateless API can skip it
If the API authenticates with a bearer token in the Authorization header, supplied by your own code, a forged request from another site has no way to add the header. There is nothing to protect, and Spring Security's documentation allows disabling CSRF there:
http.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));Conditions: no session cookie, no cookie-based authentication, no HTTP Basic credentials remembered by the browser. If the same application also serves a browser UI with sessions, keep CSRF on for those paths.
SameSite cookies
The SameSite attribute tells the browser not to send the cookie on cross-site requests:
server.servlet.session.cookie.same-site=lax
server.servlet.session.cookie.secure=true
server.servlet.session.cookie.http-only=trueLax (the default in modern browsers when unset) sends the cookie on top-level navigation by GET and withholds it from cross-site POST, which stops the classic attack. Strict withholds it from all cross-site requests, which can annoy users arriving by link. SameSite is a strong second layer and behavior differs in older browsers, so keep the token.
Never change state on GET
A GET request needs no token, so an endpoint like GET /transfer?to=... can be triggered by an image tag. Use POST, PUT or DELETE for anything that changes state, as the REST rules say (REST API design rules).
Plain Jakarta EE and servlets
Jakarta EE has no built-in CSRF protection. Options:
- Synchronizer token. Put a random token (from
SecureRandom) in the session, include it as a hidden field in each form and compare it in a servlet filter on state-changing methods. - Origin and Referer checks. Compare the
Originheader with your site's origin and reject mismatches. Simple and not a complete protection alone, since some requests omit the header. - A library. OWASP CSRFGuard provides a filter and JavaScript support.
@WebFilter("/*")
public class CsrfFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
if (!"GET".equals(request.getMethod()) && !"HEAD".equals(request.getMethod())) {
String sent = request.getHeader("X-CSRF-Token");
Object expected = request.getSession().getAttribute("csrfToken");
if (sent == null || !MessageDigest.isEqual(sent.getBytes(UTF_8), String.valueOf(expected).getBytes(UTF_8))) {
((HttpServletResponse) res).sendError(403);
return;
}
}
chain.doFilter(req, res);
}
}MessageDigest.isEqual compares in constant time. In JSF, the framework protects view state with its own token for postbacks.
Testing
Spring tests add a token with .with(csrf()). Also test that a POST without the token is rejected (403), so a refactoring cannot silently remove the protection.
A complete Spring Boot configuration for a session-based app
Pulling the pieces together, here is the configuration for an application that serves HTML with a session cookie and also has a small JavaScript front end:
@Configuration
class WebSecurityConfig {
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
CsrfTokenRequestAttributeHandler handler = new CsrfTokenRequestAttributeHandler();
handler.setCsrfRequestAttributeName(null);
return http
.authorizeHttpRequests(a -> a
.requestMatchers("/login", "/assets/**").permitAll()
.anyRequest().authenticated())
.formLogin(Customizer.withDefaults())
.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(handler))
.build();
}
}Setting the request attribute name to null makes the token load on each request, which is what a single-page front end that reads the cookie needs. The JavaScript side copies the cookie into the header on every state-changing call:
function csrfToken() {
return document.cookie
.split('; ')
.find((row) => row.startsWith('XSRF-TOKEN='))
?.split('=')[1];
}
async function post(url, body) {
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-XSRF-TOKEN': decodeURIComponent(csrfToken() ?? ''),
},
body: JSON.stringify(body),
});
if (response.status === 403) {
throw new Error('Request rejected: CSRF token missing or expired');
}
return response.json();
}A 403 here has a specific meaning. Either the cookie was never set (the first request after login did not load a page that issues it), or the session expired and the token with it. Tell the user to reload, not to retry with the same token.
Server-rendered forms
With Thymeleaf, the token is added for you inside th:action. In a template that builds the form by hand, include it explicitly:
<form method="post" action="/transfer">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<input name="amount" type="number" min="1"/>
<button type="submit">Send</button>
</form>A request that omits _csrf is rejected before the controller runs, so the handler method needs no token code at all. That is the point of doing it in a filter.
Tests that keep the protection in place
CSRF is a security control that has no visible symptom when it is removed, so it needs tests in both directions. A request with a token is accepted, and a request without one is not:
@SpringBootTest
@AutoConfigureMockMvc
class CsrfTest {
@Autowired MockMvc mvc;
@Test
@WithMockUser
void postWithoutTokenIsForbidden() throws Exception {
mvc.perform(post("/transfer").param("amount", "10"))
.andExpect(status().isForbidden());
}
@Test
@WithMockUser
void postWithTokenIsAccepted() throws Exception {
mvc.perform(post("/transfer").param("amount", "10").with(csrf()))
.andExpect(status().is3xxRedirection());
}
@Test
@WithMockUser
void tokenFromAnotherSessionIsRejected() throws Exception {
mvc.perform(post("/transfer").param("amount", "10")
.with(csrf().useInvalidToken()))
.andExpect(status().isForbidden());
}
}If someone adds csrf.disable() to make a failing test pass, the first test is the one that fails next, and the reviewer sees why.
The attack, from the attacker's side
It helps to see the page that exploits a missing token. Hosted on any other origin, this document submits itself the moment a logged-in user opens it:
<html>
<body onload="document.forms[0].submit()">
<form method="post" action="https://bank.example.com/transfer">
<input type="hidden" name="to" value="attacker-account"/>
<input type="hidden" name="amount" value="5000"/>
</form>
</body>
</html>Against a protected application, the browser still sends the session cookie, the server finds no matching token and answers 403. Against an unprotected one, with a SameSite=None cookie or an old browser, the money moves. Running this page against your own staging environment is the quickest way to show a colleague why the token cannot be skipped, and it takes five minutes.
Defense in depth for the edges
Add one more check that costs a few lines: reject state-changing requests whose Origin header names a different site. Browsers send Origin on cross-site POST requests, so a mismatch is a strong signal:
@Component
class OriginCheckFilter extends OncePerRequestFilter {
private static final Set<String> SAFE = Set.of("GET", "HEAD", "OPTIONS");
private final String allowedOrigin = "https://app.example.com";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String origin = request.getHeader("Origin");
if (!SAFE.contains(request.getMethod()) && origin != null && !origin.equals(allowedOrigin)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Cross-site request rejected");
return;
}
chain.doFilter(request, response);
}
}It does not replace the token, because some clients omit Origin, and it fails open for them by design so that legitimate non-browser callers keep working. As a second layer it removes whole classes of mistakes at almost no cost.
Where this does not apply
CSRF is unrelated to cross-origin resource sharing: CORS controls which sites may read responses, and CSRF concerns which sites can cause requests (CORS errors). Login CSRF and token leakage in URLs are separate issues. The Spring Security CSRF documentation and the OWASP CSRF Prevention Cheat Sheet are the primary sources.


