【问题标题】:Spring Boot. CORS. 'allowCredentials = false' doesn't work弹簧靴。 CORS。 'allowCredentials = false' 不起作用
【发布时间】:2021-09-17 04:40:53
【问题描述】:

我的 Spring Boot (2.4.4) 应用程序中有下一个 CORS 配置:

@Configuration
public class CORSConfiguration {
    @Bean
    public WebMvcConfigurer cors() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*");
            }
        };
    }
}

在某个时间点,我开始遇到下一个异常:

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.

之后,我根据answer 修复了我的配置:

registry.addMapping("/**").allowedOriginPatterns("*");

之后,CORS 的问题就消失了。据我了解,我不能将allowedOrigins("*") 与allowCredentials(true) 一起使用。好的,很清楚。但我根本没有在我的代码中添加allowCredentials(true)。也许这是默认值(?)。

然后我决定用下一个方式编写我的配置:

registry.addMapping("/**").allowCredentials(false).allowedOrigins("*");

CORS 和异常的问题又回来了。尽管我将以下值指定为 allowCredentials(false),但为什么 Spring 在内部某处设置了 allowCredentials(true)。 我错了什么?或者为什么 Spring 在某些情况下会覆盖 allowCredentials 的值?


我的 CORS 请求失败

请求标头:

OPTIONS /list/1054/participant-list/info HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: GET
Access-Control-Request-Headers: content-type
Referer: http://localhost:13000/
Origin: http://localhost:13000
Connection: keep-alive

响应标头:

HTTP/1.1 500 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,HEAD,POST
Access-Control-Allow-Headers: content-type
Access-Control-Max-Age: 1800
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length: 0
Date: Tue, 06 Jul 2021 14:15:16 GMT
Connection: close

【问题讨论】:

    标签: java spring spring-boot cors


    【解决方案1】:

    试试这个,并确保添加客户端的正确来源,并将所需的允许方法放在那里。我只是随意放在那里

    public void addCorsMappings(CorsRegistry registry) {
             registry.addMapping("/**")
                    .allowedOrigins("http://localhost:13000")              
         .allowedMethods("HEAD","GET","POST","PUT","DELETE","PATCH").allowedHeaders("*");       
    }
    

    【讨论】:

    • 这和allowCredentials(true)有什么关系?
    猜你喜欢
    • 2016-10-21
    • 2018-07-10
    • 2020-04-20
    • 2018-09-16
    • 2017-04-29
    • 2017-11-14
    • 2017-12-22
    • 1970-01-01
    • 2018-09-29
    相关资源
    最近更新 更多