Spring Boot enabling CORS by application.properties

This is not very clear in the official Spring documentation, and it is very easy to be misled by the official Spring Boot documentation.

The truth is that you CANNOT set the global CORS congfiguration using the application.properties file. You HAVE TO use JavaConfig as described by the Cors chapter from Spring Framework Documentation.

Just use the @EnableWebMvc annotation on a @Configuration class that implements WebMvcConfigurer and overrides the addCorsMappings method as follows:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
            .allowedOrigins("http://domain2.com")
            .allowedMethods("PUT", "DELETE")
            .allowedHeaders("header1", "header2", "header3")
            .exposedHeaders("header1", "header2")
            .allowCredentials(false).maxAge(3600);
    }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)