I am implementing CORS config for my application, where I use SpringSecurity for global configuration and also @CrossOrigin
with stricter CORS rules than in my global configuration on a specific endpoint.
My @CrossOrigin
annotated endpoint rule is ignored, allowing any cross-origin request to pass. However, my understanding is that at first Spring Security's CorsFilter
should allow request and later some HandlerInterceptor
should find @CrossOrigin
annotation and performs second CORS check too.
Can those two CORS configuration be used together, or once I oped-in to Security CORS configuration I should setup everything there?
.cors(withDefaults())
@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", superPermissiveConfiguration())
return source
}
@GetMapping("/set-csrf-cookie")
@ResponseStatus(HttpStatus.OK)
@CrossOrigin(origin = "https://<someURL>/") // UI application URL
fun setCsrfCookie(){}
I expect @CrossOrigin
annotated endpoint will be checked after CorsFilter
and overwrite the global configuration.
I am implementing CORS config for my application, where I use SpringSecurity for global configuration and also @CrossOrigin
with stricter CORS rules than in my global configuration on a specific endpoint.
My @CrossOrigin
annotated endpoint rule is ignored, allowing any cross-origin request to pass. However, my understanding is that at first Spring Security's CorsFilter
should allow request and later some HandlerInterceptor
should find @CrossOrigin
annotation and performs second CORS check too.
Can those two CORS configuration be used together, or once I oped-in to Security CORS configuration I should setup everything there?
.cors(withDefaults())
@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", superPermissiveConfiguration())
return source
}
@GetMapping("/set-csrf-cookie")
@ResponseStatus(HttpStatus.OK)
@CrossOrigin(origin = "https://<someURL>/") // UI application URL
fun setCsrfCookie(){}
I expect @CrossOrigin
annotated endpoint will be checked after CorsFilter
and overwrite the global configuration.
- 1 the rules for how the annotation works with global configuration is stated in the docs docs.spring.io/spring-framework/docs/current/javadoc-api//… they are additive, meaning local configuration will add onto the global one. – Toerktumlare Commented Mar 14 at 23:11
1 Answer
Reset to default -2I see an issue because Spring Security takes full control of CORS once you enable http.cors(withDefaults())
, which means @CrossOrigin
on your controller gets ignored.
Option 1: Remove the global CORS config from Spring Security.
Option 2: Instead of using @CrossOrigin
, configure CORS rules per endpoint.