#Java Spring Security Cors error

8 messages · Page 1 of 1 (latest)

inland pendant
#

I'm trying to enable cors between browser and server api because website shows cors error. I try to add further bean:

// Used by Spring Security if CORS is enabled.
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source =
            new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

But then I get an error:

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.
    at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:516) ~[spring-web-6.0.7.jar:6.0.7]
    at org.springframework.web.cors.CorsConfiguration.checkOrigin(CorsConfiguration.java:620) ~[spring-web-6.0.7.jar:6.0.7]
//...

How to solve this? Should I remove config.addAllowedOrigin("*"); line? Or should I ask exact url to my UI: "http://localhost:3000/" What if this url will be changed in production?

sinful karmaBOT
#

This post has been reserved for your question.

Hey @inland pendant! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

iron berry
#

ig you should list all allowed domains with addAllowedOrigin

#

if the domain changes, change it there as well

inland pendant
#

currently this : config.addAllowedOriginPattern("*"); helped

#

instead of config.addAllowedOrigin("*");

#

but with asterisk any request from any origin can be accepted