CORS lets your web app ask for resources from another website safely. Configuring it in security helps control who can access your backend.
CORS configuration in Security in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.cors(cors -> cors.configurationSource(request -> { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(List.of("https://example.com")); config.setAllowedMethods(List.of("GET", "POST")); config.setAllowedHeaders(List.of("Authorization", "Content-Type")); return config; })) .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()); return http.build(); }
You define CORS rules inside the security filter chain.
Use cors.configurationSource to customize allowed origins, methods, and headers.
http.cors(cors -> cors.configurationSource(request -> {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://myfrontend.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT"));
return config;
}))http.cors(cors -> cors.configurationSource(request -> {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOriginPattern("*");
config.addAllowedMethod("*");
config.addAllowedHeader("*");
return config;
}))This Spring Boot security config allows cross-origin requests only from https://trustedsite.com with GET and POST methods. It also requires authentication for all requests.
package com.example.demo; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.web.cors.CorsConfiguration; import java.util.List; @Configuration public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.cors(cors -> cors.configurationSource(request -> { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(List.of("https://trustedsite.com")); config.setAllowedMethods(List.of("GET", "POST")); config.setAllowedHeaders(List.of("Authorization", "Content-Type")); return config; })) .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .httpBasic(); return http.build(); } }
Always specify allowed origins explicitly to avoid security risks.
Use addAllowedOriginPattern("*") only if you understand the risks.
Test CORS settings using browser DevTools Network tab to see request headers and responses.
CORS configuration controls which websites can call your backend.
In Spring Security, configure CORS inside the security filter chain.
Always restrict origins and methods to keep your app safe.
Practice
Solution
Step 1: Understand CORS role in web security
CORS (Cross-Origin Resource Sharing) controls which external domains can call your backend APIs.Step 2: Identify the purpose in Spring Boot security
Configuring CORS in Spring Security allows safe cross-site requests by specifying allowed origins and methods.Final Answer:
To control which external websites can access your backend resources -> Option AQuick Check:
CORS controls access origins = A [OK]
- Confusing CORS with authentication
- Thinking CORS improves database speed
- Assuming CORS styles frontend
Solution
Step 1: Recall Spring Security CORS enabling syntax
Spring Security uses the methodhttp.cors()to enable CORS support.Step 2: Identify the correct chaining method
The correct chaining to disable CSRF and enable CORS ishttp.cors().and().csrf().disable();Final Answer:
http.cors().and().csrf().disable(); -> Option DQuick Check:
Enable CORS with http.cors() = C [OK]
- Using non-existent methods like enableCors()
- Forgetting to chain with .and()
- Confusing CORS enabling with CSRF
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("https://example.com", "https://app.example.com"));
configuration.setAllowedMethods(List.of("GET", "POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}Solution
Step 1: Analyze allowed origins list
The code sets allowed origins explicitly to "https://example.com" and "https://app.example.com".Step 2: Understand effect on requests
Only requests coming from these two origins will be accepted; others will be blocked by CORS policy.Final Answer:
Only requests from https://example.com and https://app.example.com are allowed -> Option CQuick Check:
Allowed origins = example.com and app.example.com = D [OK]
- Assuming all origins allowed by default
- Confusing allowed methods with allowed origins
- Thinking configuration is incomplete without headers
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins("*");
configuration.setAllowedMethods(List.of("GET", "POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}Solution
Step 1: Check setAllowedOrigins parameter type
The methodsetAllowedOriginsrequires a List<String>, but the code passes a single String "*".Step 2: Understand correct usage for wildcard
To allow all origins, useList.of("*")instead of a plain string.Final Answer:
setAllowedOrigins expects a list, not a single string -> Option BQuick Check:
Allowed origins must be List<String> = B [OK]
- Passing a string instead of a list to setAllowedOrigins
- Ignoring method parameter types
- Assuming missing HTTP methods cause errors here
Solution
Step 1: Understand wildcard origin allowance
UsingsetAllowedOrigins(List.of("*"))is deprecated and may cause issues; instead,setAllowedOriginPatternssupports wildcards properly.Step 2: Check allowed methods correctness
Only GET and POST methods are allowed as required.Final Answer:
configuration.setAllowedOriginPatterns(List.of("*")); configuration.setAllowedMethods(List.of("GET", "POST")); -> Option AQuick Check:
Use allowedOriginPatterns for wildcard origins = A [OK]
- Using setAllowedOrigins with "*" string
- Allowing extra HTTP methods by mistake
- Passing string instead of list to allowed origins
