Cors Error when using CorsFilter and spring security

Viewed 28622

I'm building an API Service using Spring Boot. It uses Basic Auth for the authentication. When clients try to connect to the API, they will get CORS error.

On the Spring Boot, it throws 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.

I have tried to find the example of allowedOriginPatterns usage but not found yet. Even for its document -https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/CorsRegistration.html#allowedOriginPatterns-java.lang.String... I still don't know what is the pattern I have to put inside config.allowedOriginPatterns();

Below is my CorsFilter code,

@Configuration
public class RequestCorsFilter {

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.setAllowedOrigins(Collections.singletonList("*"));
        config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "responseType", "Authorization"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }      

}

And here is my Authentication code,

@Configuration
@EnableWebSecurity
public class AuthenConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
        throws Exception {
    auth
    .inMemoryAuthentication()
    .withUser("thor").password("{noop}P@ssw00rd")
    .authorities("USER");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs", 
            "/swagger-resources/**", 
            "/configuration/ui",
            "/configuration/security", 
            "/swagger-ui.html",
            "/webjars/**"
        };

        http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .antMatchers(AUTH_WHITELIST).permitAll() // whitelist URL permitted
            .antMatchers("/api").authenticated(); // others need auth
    }

}
5 Answers

Use config.setAllowedOriginPatterns("*") instead of config.setAllowedOrigins(Collections.singletonList("*"));

config.setAllowedOrigins(Collections.singletonList("*"));

This line has to be changed. You should list all servers, that should have access to your application.

E.g. you use angular, so the development server for the frontend is http://localhost:4200. Your server in production is https://you.server.domain.com

Then your config List should look like this

config.setAllowedOrigins(List.of("http://localhost:4200","https://you.server.domain.com"));

This cannot set to true when you want to have the wildcard "*" in your origin.

config.setAllowCredentials(true);

So just remove it

Q:allowCredentials is true, allowedOrigins cannot contain the special value since that cannot

this can help for to resolve the issue :https://chowdera.com/2022/03/202203082045152102.html

terms of settlement Cross domain configuration error , take .allowedOrigins Replace with .allowedOriginPatterns that will do . @Configuration public class CorsConfig {

private CorsConfiguration buildConfig() {

    CorsConfiguration corsConfiguration = new CorsConfiguration();
    //corsConfiguration.addAllowedOrigin("*");
    //  Cross domain configuration error , take .allowedOrigins Replace with .allowedOriginPatterns that will do .
    //  Set the domain name that allows cross domain requests 
    corsConfiguration.addAllowedOriginPattern("*");
    corsConfiguration.addAllowedHeader("*");
    //  Set allowed methods 
    corsConfiguration.addAllowedMethod("*");
    //  Whether to allow certificates 
    corsConfiguration.setAllowCredentials(true);
    //  Cross domain allow time 
    corsConfiguration.setMaxAge(3600L);
    return corsConfiguration;
}

@Bean
public CorsFilter corsFilter() {

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", buildConfig());
    return new CorsFilter(source);
}

} class:If through the realization of WebMvcConfigurer The form of the interface , Modify as follows : @Configuration public class CorsConfig implements WebMvcConfigurer {

/** *  Turn on cross domain  */
@Override
public void addCorsMappings(CorsRegistry registry) {

    //  Set routes that allow cross domain routing 
    registry.addMapping("/**")
            //  Set the domain name that allows cross domain requests 
            //.allowedOrigins("*")  
            // Cross domain configuration error , take .allowedOrigins Replace with .allowedOriginPatterns that will do .
            .allowedOriginPatterns("*")
            //  Whether to allow certificates (cookies)
            .allowCredentials(true)
            //  Set allowed methods 
            .allowedMethods("*")
            //  Cross domain allow time 
            .maxAge(3600);
}

}

Related