With SpringBoot 2 Spring Security, The code below perfectly resolved Cors issues
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("*")); // <-- you may change "*"
configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Arrays.asList(
"Accept", "Origin", "Content-Type", "Depth", "User-Agent", "If-Modified-Since,",
"Cache-Control", "Authorization", "X-Req", "X-File-Size", "X-Requested-With", "X-File-Name"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean() {
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(corsConfigurationSource()));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
Then for the WebSecurity Configuration, I added this
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().disable()
.and()
.authorizeRequests()
.antMatchers("/oauth/tokeen").permitAll()
.antMatchers(HttpMethod.GET, "/").permitAll()
.antMatchers(HttpMethod.POST, "/").permitAll()
.antMatchers(HttpMethod.PUT, "/").permitAll()
.antMatchers(HttpMethod.DELETE, "/**").permitAll()
.antMatchers(HttpMethod.OPTIONS, "*").permitAll()
.anyRequest().authenticated()
.and().cors().configurationSource(corsConfigurationSource());
}