diff --git a/src/docs/asciidoc/web/webflux-cors.adoc b/src/docs/asciidoc/web/webflux-cors.adoc new file mode 100644 index 00000000000..9dcbbdaced2 --- /dev/null +++ b/src/docs/asciidoc/web/webflux-cors.adoc @@ -0,0 +1,207 @@ +[[webflux-cors]] += CORS + + +== Introduction + +For security reasons, browsers prohibit AJAX calls to resources residing outside the +current origin. For example, as you're checking your bank account in one tab, you +could have the evil.com website open in another tab. The scripts from evil.com should not +be able to make AJAX requests to your bank API (e.g., withdrawing money from your account!) +using your credentials. + +http://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] +(CORS) is a http://www.w3.org/TR/cors/[W3C specification] implemented by +http://caniuse.com/#feat=cors[most browsers] that allows you to specify in a flexible +way what kind of cross domain requests are authorized, instead of using some less secured +and less powerful hacks like IFRAME or JSONP. + +Spring WebFlux supports CORS out of the box. CORS requests, including preflight ones with an `OPTIONS` method, +are automatically dispatched to the various registered ``HandlerMapping``s. They handle +CORS preflight requests and intercept CORS simple and actual requests thanks to a +{api-spring-framework}/web/cors/reactive/CorsProcessor.html[CorsProcessor] +implementation (https://github.com/spring-projects/spring-framework/blob/master/spring-web/src/main/java/org/springframework/web/cors/reactive/DefaultCorsProcessor.java[DefaultCorsProcessor] +by default) in order to add the relevant CORS response headers (like `Access-Control-Allow-Origin`) +based on the CORS configuration you have provided. + + +[[webflux-cors-controller]] +== @CrossOrigin + +You can add an +{api-spring-framework}/web/bind/annotation/CrossOrigin.html[`@CrossOrigin`] +annotation to your `@RequestMapping` annotated handler method in order to enable CORS on +it. By default `@CrossOrigin` allows all origins and the HTTP methods specified in the +`@RequestMapping` annotation: + +[source,java,indent=0] +[subs="verbatim,quotes"] +---- +@RestController +@RequestMapping("/account") +public class AccountController { + + @CrossOrigin + @GetMapping("/{id}") + public Mono retrieve(@PathVariable Long id) { + // ... + } + + @DeleteMapping("/{id}") + public Mono remove(@PathVariable Long id) { + // ... + } +} +---- + +It is also possible to enable CORS for the whole controller: + +[source,java,indent=0] +[subs="verbatim,quotes"] +---- +@CrossOrigin(origins = "http://domain2.com", maxAge = 3600) +@RestController +@RequestMapping("/account") +public class AccountController { + + @GetMapping("/{id}") + public Mono retrieve(@PathVariable Long id) { + // ... + } + + @DeleteMapping("/{id}") + public Mono remove(@PathVariable Long id) { + // ... + } +} +---- + +In the above example CORS support is enabled for both the `retrieve()` and the `remove()` +handler methods, and you can also see how you can customize the CORS configuration using +`@CrossOrigin` attributes. + +You can even use both controller-level and method-level CORS configurations; Spring will +then combine attributes from both annotations to create merged CORS configuration. + +[source,java,indent=0] +[subs="verbatim,quotes"] +---- +@CrossOrigin(maxAge = 3600) +@RestController +@RequestMapping("/account") +public class AccountController { + + @CrossOrigin("http://domain2.com") + @GetMapping("/{id}") + public Account retrieve(@PathVariable Long id) { + // ... + } + + @DeleteMapping("/{id}") + public void remove(@PathVariable Long id) { + // ... + } +} +---- + + +[[webflux-cors-java-config]] +== Java Config + +In addition to fine-grained, annotation-based configuration you'll probably want to +define some global CORS configuration as well. This is similar to using filters but can +be declared within Spring WebFlux and combined with fine-grained `@CrossOrigin` configuration. +By default all origins and `GET`, `HEAD`, and `POST` methods are allowed. + +Enabling CORS for the whole application is as simple as: + +[source,java,indent=0] +[subs="verbatim,quotes"] +---- +@Configuration +@EnableWebFlux +public class WebConfig implements WebFluxConfigurer { + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**"); + } +} +---- + +You can easily change any properties, as well as only apply this CORS configuration to a +specific path pattern: + +[source,java,indent=0] +[subs="verbatim,quotes"] +---- +@Configuration +@EnableWebFlux +public class WebConfig implements WebFluxConfigurer { + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/api/**") + .allowedOrigins("http://domain2.com") + .allowedMethods("PUT", "DELETE") + .allowedHeaders("header1", "header2", "header3") + .exposedHeaders("header1", "header2") + .allowCredentials(false).maxAge(3600); + } +} +---- + + +[[webflux-cors-webfilter]] +== CORS WebFilter + +You can apply CORS support through the built-in +{api-spring-framework}/web/cors/reactive/CorsWebFilter.html[`CorsWebFilter`], which is a +good fit with <>. + +To configure the filter, you can declare a `CorsWebFilter` bean and pass a +`CorsConfigurationSource` to its constructor: + +[source,java,indent=0] +---- +@Bean +CorsWebFilter corsFilter() { + CorsConfiguration config = new CorsConfiguration(); + config.setAllowCredentials(true); + config.addAllowedOrigin("http://domain1.com"); + config.addAllowedHeader("*"); + config.addAllowedMethod("*"); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", config); + + return new CorsWebFilter(source); +} +---- + +You can also easily permit all cross-origin requests for GET, HEAD, and POST requests by writing +[source,java,indent=0] + +---- +@Bean +CorsWebFilter corsFilter() { + return new CorsWebFilter(exchange -> new CorsConfiguration().applyPermitDefaultValues()); +} +---- + + +[[webflux-cors-customizations]] +== Advanced Customization + +{api-spring-framework}/web/cors/CorsConfiguration.html[CorsConfiguration] +allows you to specify how the CORS requests should be processed: allowed origins, headers, methods, etc. +It can be provided in various ways: + + * {api-spring-framework}/web/reactive/handler/AbstractHandlerMapping.html#setCorsConfigurations-java.util.Map-[`AbstractHandlerMapping#setCorsConfigurations()`] + allows to specify a `Map` with several {api-spring-framework}/web/cors/CorsConfiguration.html[CorsConfiguration] + instances mapped to path patterns like `/api/**`. + * Subclasses can provide their own `CorsConfiguration` by overriding the + `AbstractHandlerMapping#getCorsConfiguration(Object, ServerWebExchange)` method. + * Handlers can implement the {api-spring-framework}/web/cors/reactive/CorsConfigurationSource.html[`CorsConfigurationSource`] + interface in order to provide a {api-spring-framework}/web/cors/CorsConfiguration.html[CorsConfiguration] + instance for each request. diff --git a/src/docs/asciidoc/web/webflux-functional.adoc b/src/docs/asciidoc/web/webflux-functional.adoc index 63d6cf94daf..69668a9a66a 100644 --- a/src/docs/asciidoc/web/webflux-functional.adoc +++ b/src/docs/asciidoc/web/webflux-functional.adoc @@ -241,3 +241,8 @@ RouterFunction filteredRoute = You can see in this example that invoking the `next.handle(ServerRequest)` is optional: we only allow the handler function to be executed when access is allowed. + +[NOTE] +==== +CORS support for functional endpoints is provided via a dedicated <>. +==== diff --git a/src/docs/asciidoc/web/webflux.adoc b/src/docs/asciidoc/web/webflux.adoc index e18ee74dd5f..37b3ad70b6a 100644 --- a/src/docs/asciidoc/web/webflux.adoc +++ b/src/docs/asciidoc/web/webflux.adoc @@ -1448,6 +1448,7 @@ from the base class and you can still have any number of other ``WebMvcConfigure the classpath. +include::webflux-cors.adoc[leveloffset=+1] [[webflux-http2]] @@ -1461,4 +1462,4 @@ For more details please check out the https://github.com/spring-projects/spring-framework/wiki/HTTP-2-support[HTTP/2 wiki page]. Currently Spring WebFlux does not support HTTP/2 with Netty. There is also no support for -pushing resources programmatically to the client. \ No newline at end of file +pushing resources programmatically to the client.