SpringbootWhen allowCredentials is true, allowedOrigins cannot contain the special value “*“

Posted 幽灵雾

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringbootWhen allowCredentials is true, allowedOrigins cannot contain the special value “*“相关的知识,希望对你有一定的参考价值。

【问题现象】

在前端跨域访问后端接口时,有时会报如下错误,如图:

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中,跨域配置代码如下,实现了WebMvcConfigurer接口的addCorsMappings(CorsRegistry registry)方法:

@Component
public class WebMvcConfig implements WebMvcConfigurer 

    @Override
    public void addCorsMappings(CorsRegistry registry) 
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*");
    

【原因】

allowedOrigins、allowCredentials一般为一对出现,如果设置了allowCredentials(true),表示允许证书,这是allowedOrigins就不能写通配符"*"了,而需要枚举出所有固定的域来告知可跨域的范围。

【解决】

出现这种问题,可以使用.allowedOriginPatterns(““)来代替allowCredentials(””)即可,如图:

@Component
public class WebMvcConfig implements WebMvcConfigurer 

    @Override
    public void addCorsMappings(CorsRegistry registry) 
        registry.addMapping("/**")
//                .allowedOrigins("*")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*");
    

以上是关于SpringbootWhen allowCredentials is true, allowedOrigins cannot contain the special value “*“的主要内容,如果未能解决你的问题,请参考以下文章

SpringbootWhen allowCredentials is true, allowedOrigins cannot contain the special value “*“

SpringbootWhen allowCredentials is true, allowedOrigins cannot contain the special value “*“

如何使用 http 解决 VUE 中的 CORS 问题?