Enabling CORS globally in Spring Boot

You could indeed define your own Filter as you mentioned in your answer. Spring already has such a CorsFilter already though, so you don’t have to create one yourself. Just register it as a bean and it should work:

public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    // Don't do this in production, use a proper list  of allowed origins
    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);

Leave a Comment