一直使用的都是统一配置的CorsConfig文件,之前一直没注意,直到发现服务本地没问题,在linux服务器,配置域名并启动,某些接口会报以下异常.简而言之就是 Access-Control-Allow-Origin 跨域问题.
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.
问题的原因是该配置仅适用于 SpringBoot 2.4 之前,如果你在该版本后启用,
allowCredentials(true)
的情况下是不被允许的。因为 allowCredentials(true)
的前提是你必须显式列出允许的域名,而不能使用 "*"
来允许所有来源。
corsConfiguration.addAllowedOrigin("*");
所以在 SpringBoot 2.4 之后建议使用以下配置:
corsConfiguration.addAllowedOriginPattern("*");
当然如果你使用的还是 corsConfiguration.addAllowedOrigin("*"); ,你可以通过 @CrossOrigin 来解决特定接口的问题.
直接贴码,哈哈.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* 跨域配置
* 2025-04-23
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许所有来源 SpringBoot 2.4 版本之前使用
// corsConfiguration.addAllowedOrigin("*");
// 允许所有来源 SpringBoot 2.4 版本之后使用
corsConfiguration.addAllowedOriginPattern("*");
// 允许所有来源的模式
// 允许任何消息头
corsConfiguration.addAllowedHeader("*");
// 允许任何方法
corsConfiguration.addAllowedMethod("*");
// 是否允许携带cookie信息
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}