问题
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)
}
}
回答1:
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:
https://github.com/spring-projects/spring-framework/blob/00d2606b000f9bdafbd7f4a16b6599fb51b53fa4/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/CorsRegistration.java#L61
https://github.com/spring-projects/spring-framework/blob/31aed61d1543f9f24a82a204309c0afb71dd3912/spring-web/src/main/java/org/springframework/web/cors/CorsConfiguration.java#L122
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(","));
}
}
回答2:
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
回答3:
in application.properties put
endpoints.cors.allowed-origins=http://domain1.com,http://domain2.com,http://domain3.com
Spring Boot docs for properties
http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
回答4:
This would not work, try instead :
registry.addMapping("/api/**")
.allowedOrigins(
"http://domain1.com",
"http://domain2.com",
"http://domain3.com")
see also spring reference cors
回答5:
If you're using a Global CORS with Springboot and want to add multiple domains, this is how I've done it:
In your property file, you can add your property and domains as below:
allowed.origins=*.someurl.com,*.otherurl.com,*.someotherurl.com
And your your Config Class:
@EnableWebMvc
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);
@Value("#{'${allowed.origins}'.split(',')}")
private List<String> rawOrigins;
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
logger.info("Adding CORS to the service");
registry.addMapping("/**")
.allowedOrigins(getOrigin())
.allowedMethods(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.OPTIONS.name())
.allowedHeaders(HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE, "accessToken", "CorrelationId", "source")
.exposedHeaders(HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE, "accessToken", "CorrelationId", "source")
.maxAge(4800);
}
/**
* This is to add Swagger to work when CORS is enabled
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
};
}
public String[] getOrigin() {
int size = rawOrigins.size();
String[] originArray = new String[size];
return rawOrigins.toArray(originArray);
}
}
Hope, this helps you and others who are looking for Spring enabled CORS.
来源:https://stackoverflow.com/questions/39623211/add-multiple-cross-origin-urls-in-spring-boot