cors.adoc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. [tabs]
  10. ======
  11. Java::
  12. +
  13. [source,java,role="primary"]
  14. ----
  15. @Bean
  16. CorsConfigurationSource corsConfigurationSource() {
  17. CorsConfiguration configuration = new CorsConfiguration();
  18. configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
  19. configuration.setAllowedMethods(Arrays.asList("GET","POST"));
  20. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  21. source.registerCorsConfiguration("/**", configuration);
  22. return source;
  23. }
  24. ----
  25. Kotlin::
  26. +
  27. [source,kotlin,role="secondary"]
  28. ----
  29. @Bean
  30. fun corsConfigurationSource(): CorsConfigurationSource {
  31. val configuration = CorsConfiguration()
  32. configuration.allowedOrigins = listOf("https://example.com")
  33. configuration.allowedMethods = listOf("GET", "POST")
  34. val source = UrlBasedCorsConfigurationSource()
  35. source.registerCorsConfiguration("/**", configuration)
  36. return source
  37. }
  38. ----
  39. ======
  40. The following will disable the CORS integration within Spring Security:
  41. [tabs]
  42. ======
  43. Java::
  44. +
  45. [source,java,role="primary"]
  46. ----
  47. @Bean
  48. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  49. http
  50. // ...
  51. .cors(cors -> cors.disable());
  52. return http.build();
  53. }
  54. ----
  55. Kotlin::
  56. +
  57. [source,kotlin,role="secondary"]
  58. ----
  59. @Bean
  60. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  61. return http {
  62. // ...
  63. cors {
  64. disable()
  65. }
  66. }
  67. }
  68. ----
  69. ======