在 Spring 5 Webflux 中启用 CORS?
Enable CORS in Spring 5 Webflux?
如何在 Spring 5 Webflux 项目中启用 CORS?
我找不到任何合适的文档。
@Configuration
public class WebFluxConfig {
@Bean
public WebFluxConfigurer corsConfigurer() {
return new WebFluxConfigurerComposite() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedMethods("*");
}
};
}
}
对应于:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
对于 spring mvc.
我成功使用了这个自定义过滤器:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
@Configuration
public class CorsConfiguration {
private static final String ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN";
private static final String ALLOWED_METHODS = "GET, PUT, POST, DELETE, OPTIONS";
private static final String ALLOWED_ORIGIN = "*";
private static final String MAX_AGE = "3600";
@Bean
public WebFilter corsFilter() {
return (ServerWebExchange ctx, WebFilterChain chain) -> {
ServerHttpRequest request = ctx.getRequest();
if (CorsUtils.isCorsRequest(request)) {
ServerHttpResponse response = ctx.getResponse();
HttpHeaders headers = response.getHeaders();
headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);
headers.add("Access-Control-Max-Age", MAX_AGE);
headers.add("Access-Control-Allow-Headers",ALLOWED_HEADERS);
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
}
return chain.filter(ctx);
};
}
}
和 org.springframework.boot:spring-boot-starter-web
不应作为依赖项包含在内 - 过滤器无法使用它。
这是另一个使用 Webflux 配置器的解决方案。
旁注:它的 Kotlin 代码(从我的项目中复制),但您可以轻松地将其转换为 Java 代码。
@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
}
}
感谢@Dachstein,将 WebMvc 配置替换为 Webflux 是在此处添加全局 CORS 配置的正确方法。
@Configuration
@EnableWebFlux
public class CORSConfig implements WebFluxConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*");
}
}
这里是link官方文档
https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-cors
主要有3个选项
1) 在 rest 控制器上使用 @CrossOrigin 注释 - 它可以在 class and/or 方法级别使用
2) 从 WebFluxConfigurer 实现 addCorsMapping 方法 - 它为您提供了一个进入全局 CorsRegistry 对象的钩子
3) 定义一个 CorsWebFilter 组件 - 功能端点的不错选择
请看文档,解释的很清楚。
当我想在开发时允许 cors 并且我已经将后端与前端模块分离时,我个人使用第三个选项。
想象一下,您在后端模块上安装了 webflux,而在前端模块上安装了 React 或 angular 应用程序。在开发前端功能时,您可能希望使用 webpack-dev-server 进行热重载,同时仍然 运行 netty 上的后端 - 端口将不同,这将导致 CORS 问题。使用第三个选项,您可以轻松地 link 将 @Component 更改为 @Profile("dev") 以便在部署到产品中时启用 CORS。
如果有人想要 Zufar 的答案的 Kotlin 版本(使用 webflux 路由功能就像一个魅力)而不另外弄清楚 Kotlin 的 SAM 转换是如何工作的,这里是代码:
@Bean
fun corsFilter(): WebFilter {
return WebFilter { ctx, chain ->
val request = ctx.request
if (CorsUtils.isCorsRequest(request)) {
val response = ctx.response
val headers = response.headers
headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN)
headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS)
headers.add("Access-Control-Max-Age", MAX_AGE)
headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS)
if (request.method === HttpMethod.OPTIONS) {
response.statusCode = HttpStatus.OK
return@WebFilter Mono.empty<Void>()
}
}
chain.filter(ctx)
}
}
更新
当我开始测试它时,我发现这个解决方案有一个问题。如果你真的想允许所有方法也没关系。但是假设您只想允许 POST
和 OPTIONS
,例如。并且浏览器正在尝试发送 PUT
.
然后飞行前响应基本上会说 "hey, I can only serve POST and OPTIONS, but my HTTP status will be OK
if you give me a request with Access-Control-Request-Method=PUT
"。但是,它应该是 403 Forbidden
。
更重要的是,大多数 headers,例如 Access-Control-Allow-Methods
应该只添加到预检请求,而不是所有 CORS
请求。
解决方案:
@Bean
fun corsWebFilter(): CorsWebFilter {
val corsConfig = CorsConfiguration()
corsConfig.allowedOrigins = Arrays.asList(ALLOWED_ORIGINS)
corsConfig.maxAge = MAX_AGE.toLong()
//Notice it's singular. Can't be comma separated list
corsConfig.addAllowedMethod(ALLOWED_METHOD)
corsConfig.addAllowedHeader(ALLOWED_HEADER)
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration(MATCH_ALL_PATH_SEGMENTS, corsConfig)
return CorsWebFilter(source)
}
哪里
const val MATCH_ALL_PATH_SEGMENTS = "/**"
虽然@Dachstein 的回答是正确的,但如果您启用了安全性,它仍然可能无法正常工作。您可以在此处 https://docs.spring.io/spring-security/site/docs/current/reference/html5/#cors 阅读相关文档,但由于缺少 applyPermitDefaultValues()
方法,提供的代码可能不够。
如果是这样,请尝试以下代码:
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.applyPermitDefaultValues();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:8081"));
configuration.setAllowedMethods(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
如果使用 spring webflux security 以下代码段有效
protected ServerHttpSecurity applyCors(ServerHttpSecurity http) {
return http.cors().configurationSource(urlBasedCorsConfigurationSource()).and();
}
private UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.applyPermitDefaultValues();
// corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
corsConfiguration.setAllowedMethods(Arrays.asList("*"));
corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
UrlBasedCorsConfigurationSource ccs = new UrlBasedCorsConfigurationSource();
ccs.registerCorsConfiguration("/**", corsConfiguration);
return ccs;
}
如何在 Spring 5 Webflux 项目中启用 CORS?
我找不到任何合适的文档。
@Configuration
public class WebFluxConfig {
@Bean
public WebFluxConfigurer corsConfigurer() {
return new WebFluxConfigurerComposite() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedMethods("*");
}
};
}
}
对应于:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
对于 spring mvc.
我成功使用了这个自定义过滤器:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
@Configuration
public class CorsConfiguration {
private static final String ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN";
private static final String ALLOWED_METHODS = "GET, PUT, POST, DELETE, OPTIONS";
private static final String ALLOWED_ORIGIN = "*";
private static final String MAX_AGE = "3600";
@Bean
public WebFilter corsFilter() {
return (ServerWebExchange ctx, WebFilterChain chain) -> {
ServerHttpRequest request = ctx.getRequest();
if (CorsUtils.isCorsRequest(request)) {
ServerHttpResponse response = ctx.getResponse();
HttpHeaders headers = response.getHeaders();
headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);
headers.add("Access-Control-Max-Age", MAX_AGE);
headers.add("Access-Control-Allow-Headers",ALLOWED_HEADERS);
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
}
return chain.filter(ctx);
};
}
}
和 org.springframework.boot:spring-boot-starter-web
不应作为依赖项包含在内 - 过滤器无法使用它。
这是另一个使用 Webflux 配置器的解决方案。
旁注:它的 Kotlin 代码(从我的项目中复制),但您可以轻松地将其转换为 Java 代码。
@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
}
}
感谢@Dachstein,将 WebMvc 配置替换为 Webflux 是在此处添加全局 CORS 配置的正确方法。
@Configuration
@EnableWebFlux
public class CORSConfig implements WebFluxConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*");
}
}
这里是link官方文档
https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-cors
主要有3个选项
1) 在 rest 控制器上使用 @CrossOrigin 注释 - 它可以在 class and/or 方法级别使用
2) 从 WebFluxConfigurer 实现 addCorsMapping 方法 - 它为您提供了一个进入全局 CorsRegistry 对象的钩子
3) 定义一个 CorsWebFilter 组件 - 功能端点的不错选择
请看文档,解释的很清楚。
当我想在开发时允许 cors 并且我已经将后端与前端模块分离时,我个人使用第三个选项。
想象一下,您在后端模块上安装了 webflux,而在前端模块上安装了 React 或 angular 应用程序。在开发前端功能时,您可能希望使用 webpack-dev-server 进行热重载,同时仍然 运行 netty 上的后端 - 端口将不同,这将导致 CORS 问题。使用第三个选项,您可以轻松地 link 将 @Component 更改为 @Profile("dev") 以便在部署到产品中时启用 CORS。
如果有人想要 Zufar 的答案的 Kotlin 版本(使用 webflux 路由功能就像一个魅力)而不另外弄清楚 Kotlin 的 SAM 转换是如何工作的,这里是代码:
@Bean
fun corsFilter(): WebFilter {
return WebFilter { ctx, chain ->
val request = ctx.request
if (CorsUtils.isCorsRequest(request)) {
val response = ctx.response
val headers = response.headers
headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN)
headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS)
headers.add("Access-Control-Max-Age", MAX_AGE)
headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS)
if (request.method === HttpMethod.OPTIONS) {
response.statusCode = HttpStatus.OK
return@WebFilter Mono.empty<Void>()
}
}
chain.filter(ctx)
}
}
更新
当我开始测试它时,我发现这个解决方案有一个问题。如果你真的想允许所有方法也没关系。但是假设您只想允许 POST
和 OPTIONS
,例如。并且浏览器正在尝试发送 PUT
.
然后飞行前响应基本上会说 "hey, I can only serve POST and OPTIONS, but my HTTP status will be OK
if you give me a request with Access-Control-Request-Method=PUT
"。但是,它应该是 403 Forbidden
。
更重要的是,大多数 headers,例如 Access-Control-Allow-Methods
应该只添加到预检请求,而不是所有 CORS
请求。
解决方案:
@Bean
fun corsWebFilter(): CorsWebFilter {
val corsConfig = CorsConfiguration()
corsConfig.allowedOrigins = Arrays.asList(ALLOWED_ORIGINS)
corsConfig.maxAge = MAX_AGE.toLong()
//Notice it's singular. Can't be comma separated list
corsConfig.addAllowedMethod(ALLOWED_METHOD)
corsConfig.addAllowedHeader(ALLOWED_HEADER)
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration(MATCH_ALL_PATH_SEGMENTS, corsConfig)
return CorsWebFilter(source)
}
哪里
const val MATCH_ALL_PATH_SEGMENTS = "/**"
虽然@Dachstein 的回答是正确的,但如果您启用了安全性,它仍然可能无法正常工作。您可以在此处 https://docs.spring.io/spring-security/site/docs/current/reference/html5/#cors 阅读相关文档,但由于缺少 applyPermitDefaultValues()
方法,提供的代码可能不够。
如果是这样,请尝试以下代码:
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.applyPermitDefaultValues();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:8081"));
configuration.setAllowedMethods(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
如果使用 spring webflux security 以下代码段有效
protected ServerHttpSecurity applyCors(ServerHttpSecurity http) {
return http.cors().configurationSource(urlBasedCorsConfigurationSource()).and();
}
private UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.applyPermitDefaultValues();
// corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
corsConfiguration.setAllowedMethods(Arrays.asList("*"));
corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
UrlBasedCorsConfigurationSource ccs = new UrlBasedCorsConfigurationSource();
ccs.registerCorsConfiguration("/**", corsConfiguration);
return ccs;
}