我找到了一个有关如何在spring-boot应用程序中设置cors标头的示例。由于我们有很多起源,所以我需要添加它们。以下有效吗?
@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") } }
除非被三个域使用,否则我无法对其进行测试。但是我想确保设置了三个源,并且不仅设置了“ domain3.com”。
编辑 :理想的用例是注入一个域列表(来自application.properties),并在allowedOrigins中进行设置。可能吗
即
@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) } }
您设置的方式只会设置第三个原点,而另两个将消失。
如果要设置所有三个原点,则需要将它们作为逗号分隔的字符串传递。
@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://domain1.com","http://domain2.com" "http://domain3.com"); }
您可以在此处找到实际的代码:
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
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(",")); } }