繁体   English   中英

弹簧靴。 CORS。 'allowCredentials = false' 不起作用

[英]Spring Boot. CORS. 'allowCredentials = false' doesn't work

我在 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.

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

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

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

然后我决定以下一种方式编写我的配置:

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

CORS 和异常的问题又回来了。 为什么 Spring 在内部某处设置allowCredentials(true) ,尽管我将以下值指定为allowCredentials(false) 我有什么错? 或者为什么 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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM