Search code examples
corsspring-security-6

Bean is expected to be of type CorsFilter but was actually of type UrlBasedCorsConfigurationSource with Spring Security 6


I want to disable CORS for my frontend written in Angular, running locally on port 4200. I created a config but it doesn't seem to work.

I get this error with Spring Security 6 after trying to start the application:

Bean named 'corsFilter' is expected to be of type 
'org.springframework.web.filter.CorsFilter' but was actually of type 
'org.springframework.web.cors.UrlBasedCorsConfigurationSource'

I'm following this answer and this Spring guide.

My pom.xml

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>6.1.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>6.1.0</version>
</dependency>

My security config

@Bean
public SecurityFilterChain configureSecurity(HttpSecurity http) throws Exception {
    http
        // ...
        .cors(withDefaults());
    return http.build();
}

@Bean
public CorsConfigurationSource corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.setAllowedOrigins(List.of("https://localhost:4200"));
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);

    return source;
}

What's wrong? I use bean of type CorsConfigurationSource like they advice to me and Spring still wants CorsFilter like it was in previous versions of Spring Security?


Solution

  • Rename corsFilter to corsConfigurationSource.