Performance: CORS configuration in Security
This affects how quickly the browser can safely load resources from different origins without blocking or delays.
Jump into concepts and practice - no test required
http.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"));
config.setAllowCredentials(true);
return config;
});http.cors().and().csrf().disable(); // No specific CORS config, defaults apply| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Default or no CORS config | N/A | N/A | Blocks rendering until preflight completes | [X] Bad |
| Explicit CORS config with limited origins and methods | N/A | N/A | Allows faster resource loading, no blocking | [OK] Good |
http.cors() to enable CORS support.http.cors().and().csrf().disable();@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;
}@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;
}setAllowedOrigins requires a List<String>, but the code passes a single String "*".List.of("*") instead of a plain string.setAllowedOrigins(List.of("*")) is deprecated and may cause issues; instead, setAllowedOriginPatterns supports wildcards properly.