Issue
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
}
}
Solution
Use config.setAllowedOriginPatterns("*")
instead of config.setAllowedOrigins(Collections.singletonList("*"));
Answered By - stodi