Spring Boot enabling CORS by application.properties
We can move actual cors related urls to application.properties anyway. It works for me with Spring Boot 5.
App.java (main class):
@SpringBootApplication
public class App extends SpringBootServletInitializer {
@Autowired
private Environment env;
public static void main(String[] args) {
SpringApplication.run(ReportsApplication.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
String urls = env.getProperty("cors.urls");
CorsRegistration reg = registry.addMapping("/api/**");
for(String url: urls.split(",")) {
reg.allowedOrigins(url);
}
}
};
}
}
application.properties:
cors.urls=http://localhost:3000
Spring boot properties prefixed by endpoints.cors.* are used by Actuator so that's why it will not work with MVC endpoints.
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);
}
}
I got the answer by myself:
Just add this to application.java
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
}
};
}