Cross-site request forgery occurs when a browser sends an ambient credential, commonly a session cookie, with a state-changing request initiated by another site. Authentication alone cannot tell whether the user intended that write.
Spring Security CSRF: protect cookie-authenticated writes
Separate browser sessions from bearer clients
Spring Security enables CSRF protection for unsafe methods by default in a typical Servlet configuration. A form-backed session should render a CSRF token with the form or pass it in an appropriate request header. The server compares the submitted token with the expected token before the controller mutates state. A token stored in the session also expires with it; a stale form must be reloaded rather than retried silently.
package in.aitrove.receipts;
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;
@Configuration
class ReceiptBrowserSecurity {
@Bean
SecurityFilterChain browserSecurity(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/login").permitAll()
.requestMatchers("/receipts/**").authenticated()
.anyRequest().denyAll());
http.formLogin(Customizer.withDefaults());
http.csrf(Customizer.withDefaults());
return http.build();
}
}The example keeps Spring Security’s default CSRF behavior visible. It does not include the HTML form; rendering the actual token is a separate view concern. If the same application also serves stateless bearer-token APIs, define and test their credential boundary carefully. Disabling CSRF for the entire site because one API uses bearer tokens can expose a browser-session route.
CORS and SameSite cookie settings can add constraints, but neither replaces the CSRF decision for a cookie-authenticated write. CSRF checks add small per-request validation and token storage or retrieval; the dominant cost is usually the application write they protect.
Common Mistakes
- Sending a session cookie on a POST while omitting the token from the form or header.
- Disabling CSRF globally to make one automated test pass.
- Confusing a missing CSRF token with a bad password or missing authorization.
- Assuming a bearer API and a cookie-backed browser route have the same threat model.
Read next
Bearer POST and CSRF, CORS boundaries, and session-scoped state.
Related boundary: Spring Security OAuth2 login: callback, identity and browser session.
