CORS and CSRF Protection in Spring Boot
Learn CORS and CSRF protection in Spring Boot, including browser security, allowed origins, preflight requests, CSRF tokens, stateless APIs, and secure configuration patterns.
What You Will Learn
- What CORS protects and what it does not protect.
- How browser preflight requests work.
- Why CSRF matters for cookie-based applications.
- How to configure CORS and CSRF safely in Spring Security.
- Common production mistakes.
Introduction
CORS and CSRF are often confused because both involve browser security.
CORS controls which browser origins can call your API. CSRF protects authenticated users from unwanted state-changing requests sent by malicious sites.
CORS in Simple Terms
CORS stands for Cross-Origin Resource Sharing.
If your frontend runs on:
https://app.example.com
and your API runs on:
https://api.example.com
the browser treats this as a cross-origin request.
CORS Flow
sequenceDiagram
participant Browser
participant API
Browser->>API: OPTIONS preflight request
API-->>Browser: Allowed origins and methods
Browser->>API: Actual API request
API-->>Browser: API response
Safe CORS Configuration
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(Customizer.withDefaults())
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
);
return http.build();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://app.example.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
CSRF in Simple Terms
CSRF stands for Cross-Site Request Forgery.
It matters most when authentication is stored automatically by the browser, usually in cookies.
Example risk:
User is logged in to bank.com.
Malicious site submits a hidden POST request to bank.com.
Browser automatically sends bank.com cookies.
When to Enable or Disable CSRF
| Application Type | CSRF Recommendation |
|---|---|
| Server-rendered app with session cookies | Enable CSRF |
| Browser app using cookies | Enable CSRF |
| Stateless REST API using Authorization header bearer tokens | Usually disable CSRF |
| Mixed cookie and API setup | Review carefully |
Stateless API Example
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
);
return http.build();
}
Common Mistakes
- Allowing all origins in production.
- Using
allowCredentials(true)with broad origins. - Thinking CORS replaces authentication.
- Disabling CSRF for cookie-based applications without understanding the risk.
- Forgetting preflight OPTIONS requests.
Summary
CORS is a browser access-control mechanism. CSRF is a request-forgery protection mechanism. Configure both based on how your frontend authenticates with your backend.
Learning Path Navigation
- Series home: Spring Security Learning Path
- Previous: Rate Limiting APIs with Bucket4j and Redis
- Next: LDAP Authentication with Spring Boot
Comments
Share a question, correction, or practical insight about this article.
Checking login status...
Loading approved comments...