跨域配置如下,Springboot 版本为 2.4.1
///跨域访问配置
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true); //sessionid 多次访问一致
corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 允许任何头
corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
return new CorsFilter(source);
}
}
问题:跨域配置无效,访问接口报如下错误
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:453) ~[spring-web-5.3.2.jar:5.3.2]
at org.springframework.web.cors.CorsConfiguration.checkOrigin(CorsConfiguration.java:557) ~[spring-web-5.3.2.jar:5.3.2]
分析:
由于我是升级了 Springboot 到 2.4.1 版本之后才出现的这个问题,再结合报错信息提示不能使用*号设置允许的Origin,所以有两个解决方法。
解决方法:
1、降低 Springboot 版本
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
2、如果不降低版本,则在跨域设置时使用setAllowedOriginPatterns方法
// 跨域访问配置
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true); //sessionid 多次访问一致
// 允许访问的客户端域名
List<String> allowedOriginPatterns = new ArrayList<>();
allowedOriginPatterns.add("*");
corsConfiguration.setAllowedOriginPatterns(allowedOriginPatterns);
// corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 允许任何头
corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
return new CorsFilter(source);
}