cors.adoc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. [[webflux-cors]]
  2. = CORS
  3. Spring Framework provides https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-cors-intro[first class support for CORS].
  4. CORS must be processed before Spring Security because the pre-flight request will not contain any cookies (i.e. the `JSESSIONID`).
  5. If the request does not contain any cookies and Spring Security is first, the request will determine the user is not authenticated (since there are no cookies in the request) and reject it.
  6. The easiest way to ensure that CORS is handled first is to use the `CorsWebFilter`.
  7. Users can integrate the `CorsWebFilter` with Spring Security by providing a `CorsConfigurationSource`.
  8. For example, the following will integrate CORS support within Spring Security:
  9. ====
  10. .Java
  11. [source,java,role="primary"]
  12. ----
  13. @Bean
  14. CorsConfigurationSource corsConfigurationSource() {
  15. CorsConfiguration configuration = new CorsConfiguration();
  16. configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
  17. configuration.setAllowedMethods(Arrays.asList("GET","POST"));
  18. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  19. source.registerCorsConfiguration("/**", configuration);
  20. return source;
  21. }
  22. ----
  23. .Kotlin
  24. [source,kotlin,role="secondary"]
  25. ----
  26. @Bean
  27. fun corsConfigurationSource(): CorsConfigurationSource {
  28. val configuration = CorsConfiguration()
  29. configuration.allowedOrigins = listOf("https://example.com")
  30. configuration.allowedMethods = listOf("GET", "POST")
  31. val source = UrlBasedCorsConfigurationSource()
  32. source.registerCorsConfiguration("/**", configuration)
  33. return source
  34. }
  35. ----
  36. ====
  37. The following will disable the CORS integration within Spring Security:
  38. ====
  39. .Java
  40. [source,java,role="primary"]
  41. ----
  42. @Bean
  43. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  44. http
  45. // ...
  46. .cors(cors -> cors.disable());
  47. return http.build();
  48. }
  49. ----
  50. .Kotlin
  51. [source,kotlin,role="secondary"]
  52. ----
  53. @Bean
  54. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  55. return http {
  56. // ...
  57. cors {
  58. disable()
  59. }
  60. }
  61. }
  62. ----
  63. ====