Access-Control-Allow-Origin 后端跨域问题解决

        一直使用的都是统一配置的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);
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值