我找到了一个关于如何在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)
}
}
答案 0 :(得分:16)
在Spring启动时,有一个注释 @CrossOrigin ,它只会在响应中添加标题。
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
答案 1 :(得分:12)
您设置的方式只会设置第三个原点而另外两个将会消失。
如果你想要所有这三个来源,那么你需要传递给命令分隔的字符串。
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain1.com","http://domain2.com"
"http://domain3.com");
}
你可以在这里找到实际代码:
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 :(得分:9)
endpoints.cors.allowed-origins=http://domain1.com,http://domain2.com,http://domain3.com
属性的Spring Boot文档
http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
答案 3 :(得分:4)
这不起作用,请尝试:
registry.addMapping("/api/**")
.allowedOrigins(
"http://domain1.com",
"http://domain2.com",
"http://domain3.com")
答案 4 :(得分:2)
如果您在Springboot中使用Global CORS,并且想要添加多个域,这就是我的方法:
在您的属性文件中,您可以如下添加属性和域:
allowed.origins=*.someurl.com,*.otherurl.com,*.someotherurl.com
您的配置类:
@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);
}
}
希望,这对您和正在寻找支持Spring的CORS的其他人有帮助。
答案 5 :(得分:0)
resources / application.yaml
server: port: 8080 servlet: contextPath: /your-service jetty: acceptors: 1 maxHttpPostSize: 0 cors: origins: - http://localhost:3001 - https://app.mydomainnnn.com - https://app.yourrrrdooomain.com
config / Config.java
package com.service.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("server")
public class Config {
private int port;
private Cors cors;
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public Cors getCors() {
return this.cors;
}
public void setCors(Cors cors) {
this.cors = cors;
}
public static class Cors {
private List<String> origins = new ArrayList<>();
public List<String> getOrigins() {
return this.origins;
}
public void setOrigins(List<String> origins) {
this.origins = origins;
}
}
}
config / WebConfig.java
package com.service.config;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.ComponentScan;
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
@ComponentScan(basePackages = "com.service.controller")
@PropertySource("classpath:application.yaml")
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
private Environment environment;
@Autowired
private Config config;
@Override
public void addCorsMappings(CorsRegistry registry) {
System.out.println("configuring cors");
String[] origins = config.getCors().getOrigins().toArray(String[]::new);
System.out.println(" - origins " + Arrays.toString(origins));
registry.addMapping("/**")
.allowedOrigins(origins);
}
}
答案 6 :(得分:0)
创建您的自定义注释,并以此为API进行注释。
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@CrossOrigin
public @interface CrossOriginsList {
public String[] crossOrigins() default {
"http://domain1.com", "http://domain1.com"
"http://domain1.com", "http://domain1.com"
// Pass as many as you want
};
}
现在使用此自定义注释对API进行注释
@CrossOriginsList
public String methodName() throws Exception
{
//Business Logic
}
对我来说做得很好。!