I was trying to set CORS configs to my Spring Boot application globally in order not to use @CrossOrigin annotation in each controller or endpoint. As far as I checked Spring docs and stackoverflow, the way setting custom CORS configs is like:
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("http://localhost:3000");
configuration.addAllowedMethod("*");
configuration.addAllowedHeader("*");
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new
UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
and finally using it in SecurityFilterChain like:
@Bean
protected SecurityFilterChain securityFilterChain(final HttpSecurity http) throws Exception {
http.cors(cors -> cors.configurationSource(corsConfigurationSource()))
//.cors(Customizer.withDefaults())
.csrf(
AbstractHttpConfigurer::disable
)
//Some more configurations...
return http.build();
}
This code block should be fine according to other usages but it gives me:
Required type: CorsConfigurationSource Provided: UrlBasedCorsConfigurationSource
error due to return type of CorsConfigurationSource bean. Casting does not work either.
I am using Spring Boot 3.1.0.
Any suggestions?
I got the solution. It is kinda silly but can help the people who encounter the same problem:
I was importing UrlBasedCorsConfigurationSource from:
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
Instead of
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
So, you shouldn't import it from reactive package.