问题描述
原来在 Spring Boot 2.1、2.2、2.3
等版本时使用的跨域设置在升级到 2.4+
后失效了。
原来的跨域解决方案:
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*"); //也可用 setAllowedOrigins(List<String>) 增加多个地址
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.setMaxAge(3600L); //缓存时间(秒)
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
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:473) ~[spring-web-5.3.10.jar:5.3.10]
解决方案
方案1:
不使用 CorsFilter
,而是实现 WebMvcConfigurer
接口,重写方法 addCorsMappings
方法
@Configuration
public class CorsConfig implements WebMvcConfigurer {
/**
* 跨域配置
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders("*")
.allowedMethods("*")
.maxAge(1800);
}
}
方案2:
若想继续使用 CorsFilter
也可以,
1)将 * 改成具体的网址列表。
2)使用 addAllowedOriginPatterns
替代 addAllowedOrigin
config.addAllowedOriginPattern("*");