1) Using the @CrossOrigin annotation on a rest controller - it can be used at class and/or method level
2) Implement the addCorsMapping method from the WebFluxConfigurer - it gives you an hook into the global CorsRegistry object
3) Define a CorsWebFilter component - good choice for functional endpoints
Please look at the docs, are well explained.
Personally I use the third option when I want to allow cors while developing and I have decoupled the backend from the frontend module.
Imagine that you have webflux on a backend module while on the frontend you have a react or angular app. While developing the frontend features you might want to use webpack-dev-server for hot reloading while still running the backend on netty - the port will be different and this will cause CORS problem. With the third option you can easily link the @Component to @Profile("dev") so that when you deploy in prod CORS are enabled.
Here is another solution with the Webflux Configurer.
Side Note: Its Kotlin Code (copied from my project) but you can easily translate that to Java Code.
@Configuration
@EnableWebFlux
class WebConfig: WebFluxConfigurer
{
override fun addCorsMappings(registry: CorsRegistry)
{
registry.addMapping("/**")
.allowedOrigins("*") // any host or put domain(s) here
.allowedMethods("GET, POST") // put the http verbs you want allow
.allowedHeaders("Authorization") // put the http headers you want allow
}
}
Here is a link to the official documentation
https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-cors
There are 3 main options
1) Using the @CrossOrigin annotation on a rest controller - it can be used at class and/or method level
2) Implement the addCorsMapping method from the WebFluxConfigurer - it gives you an hook into the global CorsRegistry object
3) Define a CorsWebFilter component - good choice for functional endpoints
Please look at the docs, are well explained.
Personally I use the third option when I want to allow cors while developing and I have decoupled the backend from the frontend module.
Imagine that you have webflux on a backend module while on the frontend you have a react or angular app. While developing the frontend features you might want to use webpack-dev-server for hot reloading while still running the backend on netty - the port will be different and this will cause CORS problem. With the third option you can easily link the @Component to @Profile("dev") so that when you deploy in prod CORS are enabled.
Thanks to @Dachstein, replacing WebMvc configs with Webflux is the correct way of adding global CORS Config here.
which corresponds to:
for spring mvc.
I had success with this custom filter:
and
org.springframework.boot:spring-boot-starter-web
should not be included as dependency - filter does not work with it.Here is another solution with the Webflux Configurer.
Side Note: Its Kotlin Code (copied from my project) but you can easily translate that to Java Code.