Enabling CORS globally in Spring Boot

ghz 1years ago ⋅ 2394 views

Question

I tried to enable CORS globally like this:

@Configuration
@ComponentScan("com.example")
@EnableWebMvc
public class OriginFilter extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}

I also tried this approach:

@Configuration
public class OriginFilter implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
                .allowCredentials(true);
    }
}

But none of these worked for me.

An annotation @CrossOrigin for an individual class works, but I wanted to enable CORS it globally.


Answer

You could indeed define your own Filter as you mentioned in your answer. Spring already has such a [CorsFilter](https://docs.spring.io/spring/docs/current/javadoc- api/org/springframework/web/filter/CorsFilter.html) already though, so you don't have to create one yourself. Just register it as a bean and it should work:

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    // Don't do this in production, use a proper list  of allowed origins
    config.setAllowedOrigins(Collections.singletonList("*"));
    config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}