问题描述
SpringBoot升级后跨域请求报如下错误
代码语言:javascript复制java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:473)
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
*__checkpoint ⇢ com.xxx.cloud.gateway.config.CorsConfig$1 [DefaultWebFilterChain]
*__checkpoint ⇢ com.xxx.cloud.gateway.config.CorsConfig$$Lambda$615/1289462509 [DefaultWebFilterChain]
*__checkpoint ⇢ org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter [DefaultWebFilterChain]
*__checkpoint ⇢ com.alibaba.csp.sentinel.adapter.spring.webflux.SentinelWebFluxFilter [DefaultWebFilterChain]
*__checkpoint ⇢ HTTP GET "/api/auth/v2/api-docs" [ExceptionHandlingWebHandler]
When allowCredentials is true, allowedOrigins cannot contain the special value “*” since that cannot be set on the “Access-Control-Allow-Origin” response header. To allow credentials to a set of origins, list them explicitly or consider using “allowedOriginPatterns” instead. 翻译为: 当allowCredentials为真时, allowedorigin不能包含特殊值"", 因为不能在"Access-Control-Allow-Origin"响应头 中设置该值。要允许凭证到起源,显式地列出它们,或者考虑使用"allowedOriginPatterns"代替。
解决办法
跨域配置报错,将.allowedOrigins替换成.allowedOriginPatterns即可。
代码语言:javascript复制@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
//corsConfiguration.addAllowedOrigin("*");
// 跨域配置报错,将.allowedOrigins替换成.allowedOriginPatterns即可。
// 设置允许跨域请求的域名
corsConfiguration.addAllowedOriginPattern("*");
corsConfiguration.addAllowedHeader("*");
// 设置允许的方法
corsConfiguration.addAllowedMethod("*");
// 是否允许证书
corsConfiguration.setAllowCredentials(true);
// 跨域允许时间
corsConfiguration.setMaxAge(3600L);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
要是通过实现WebMvcConfigurer接口的形式,则按照如下修改:
代码语言:javascript复制@Configuration
public class CorsConfig implements WebMvcConfigurer {
/**
* 开启跨域
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路由
registry.addMapping("/**")
// 设置允许跨域请求的域名
//.allowedOrigins("*")
//跨域配置报错,将.allowedOrigins替换成.allowedOriginPatterns即可。
.allowedOriginPatterns("*")
// 是否允许证书(cookies)
.allowCredentials(true)
// 设置允许的方法
.allowedMethods("*")
// 跨域允许时间
.maxAge(3600);
}
}