Enable CORS globally in Spring Boot

People, I’m about to show how you can enable CORS globally in your spring boot application.

1. Configuration

Create a configuration class and annotate with @Configiration anntation. Please make sure that this class is being scanned by component scanner. If not use annotation @ComponentScan to scan your package. Subpackages will automatically be scanned.

@Configuration
public class AppConfig {
   
}

2. Configure CORS Filter

@Order(2)
@Configuration
public class AppConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("PATCH");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

3. Enable OPTIONS Request

Additionally you can enable OPTIONS request so that freakin javascript doesn’t complain.

You need to configure another Bean called DispatcherServlet

@Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServlet dispatcherServlet() {
    DispatcherServlet dispatcherServlet = new DispatcherServlet();
    dispatcherServlet.setDispatchOptionsRequest(true);
    return dispatcherServlet;
}

Well, you’re in a position to test your app right now.

 

1 thought on “Enable CORS globally in Spring Boot

Leave a Reply

Your email address will not be published. Required fields are marked *