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) } }
Enable CORS in Controller Method We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.
This @CrossOrigin annotation enables cross-origin resource sharing only for this specific method. By default, its allows all origins, all headers, and the HTTP methods specified in the @RequestMapping annotation. Also, a maxAge of 30 minutes is used.
If you want to configure allowedHeaders , methods , origins and so on, you can simply add those values to the annotation like this: @CrossOrigin(origins = "http://localhost:50029", maxAge = 3600) . Using the @CrossOrigin annotation, the Spring Security configuration becomes extremely easy. Simply add and().
In Spring boot there is an annotation @CrossOrigin which will simply add header in the response.
1. For multiple: @CrossOrigin(origins = {"http://localhost:7777", "http://someserver:8080"}) @RequestMapping(value = "/abc", method = RequestMethod.GET) @ResponseBody public Object doSomething(){ ... } 2. If you wanna allow for everyone then simply use. @CrossOrigin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With