1

I had the next CORS configuration in my Spring Boot (2.4.4) application:

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

At some point of time I started getting the next exception:

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.

After that, I fixed my configuration according with the answer:

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

After that, the problem with CORS is gone away. And as I understood, I can't use allowedOrigins("*") with allowCredentials(true). Ok, it's clear. But I didn't add allowCredentials(true) in my code at all. Perhaps this is the default value(?).

Then I decided to write my configuration the next way:

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

And the problem with CORS and exception came back. Why Spring set allowCredentials(true) somewhere inside, despite the fact that I specified the following value as allowCredentials(false). What am I wrong about? Or why Spring overrides the value of allowCredentials in some cases?


My failed CORS request

Request headers:

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

Response headers:

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
Majid Hajibaba
  • 3,105
  • 6
  • 23
  • 55
Volodya Lombrozo
  • 2,325
  • 2
  • 16
  • 34

1 Answers1

-1

Try this and make sure to add the correct origin of the client-side as well as put the needed allowed methods there. I just randomly put there

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