Spring Security defends against Cross-Site Request Forgery by requiring a unique, unpredictable CSRF token on every state-changing request, so a forged request from another site cannot be replayed without knowing that token.
A stateless microservice that only accepts requests carrying a bearer token in the Authorization header has no session cookie to forge, so the team disables CSRF via http.csrf(csrf -> csrf.disable()) while keeping CORS locked down.
// Browser app with session cookies: keep CSRF protection ON.
// A cookie-based token lets a JavaScript front end read and send it back.
@Bean
SecurityFilterChain webApp(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
.formLogin(Customizer.withDefaults())
.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.build();
}
// Stateless REST API using bearer tokens (no cookies): CSRF can be disabled
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.securityMatcher("/api/**")
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
.build();
}A concise interview answer is
Spring Security prevents CSRF by issuing a token that must accompany every state-changing request, so an attacker's forged request fails without it. I'd typically disable CSRF only for stateless, token-authenticated APIs consumed by non-browser clients, since there's no session cookie to exploit in that case.
Last updated: 1 November 2026
Previous question: What is the OAuth2 authorization code grant type?
Next question: How can you implement method-level security in a Spring application, and what are the advantages of this approach?