Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add multiple cross origin urls in spring boot

Tags:

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)     } } 
like image 228
brain storm Avatar asked Sep 21 '16 17:09

brain storm


People also ask

How do you add CORS to origin in spring boot?

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.

What is CrossOrigin annotation in spring boot?

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.

How do you handle CORS issue in spring boot?

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().


1 Answers

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 
like image 117
Sumit Sundriyal Avatar answered Nov 13 '22 03:11

Sumit Sundriyal