Issue
I found an example on how to set cors headers in spring-boot application. Since we have many origins, I need to add them. Is the following valid?
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain1.com")
.allowedOrigins("http://domain2.com")
.allowedOrigins("http://domain3.com")
}
}
I have no way to test this unless it is used by three domains. But I want to make sure I have three origins set up and not only "domain3.com" is set.
EDIT: ideal use case for is to inject a list of domains(from application.properties) and set that in allowedOrigins. Is it possible
i.e
@Value("${domainsList: not configured}")
private List<String> domains;
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins(domains)
}
}
Solution
The way you are setting will only set the third origin and the other two will be gone.
if you want all the three origins to be set then you need to pass them as comma separated Strings.
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain1.com","http://domain2.com"
"http://domain3.com");
}
you can find the actual code here:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
@PropertySource("classpath:config.properties")
public class CorsClass extends WebMvcConfigurerAdapter {
@Autowired
private Environment environment;
@Override
public void addCorsMappings(CorsRegistry registry) {
String origins = environment.getProperty("origins");
registry.addMapping("/api/**")
.allowedOrigins(origins.split(","));
}
}
Answered By - Deendayal Garg
Answer Checked By - Gilberto Lyons (JavaFixing Admin)