在 Spring Boot 中添加多个跨源 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39623211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:13:10  来源:igfitidea点击:

add multiple cross origin urls in spring boot

springspring-mvcspring-bootcors

提问by brain storm

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?

我找到了一个关于如何在 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")
    }
}

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.

除非它被三个域使用,否则我无法测试它。但我想确保我设置了三个来源,而不仅仅是设置了“domain3.com”。

EDIT: ideal use case for is to inject a list of domains(from application.properties) and set that in allowedOrigins. Is it possible

编辑:理想的用例是注入域列表(来自 application.properties)并将其设置在 allowedOrigins 中。是否可以

i.e

IE

  @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)
    }
}

回答by Sumit Sundriyal

In Spring boot there is an annotation @CrossOriginwhich will simply add header in the response.

在 Spring boot 中有一个注释@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

回答by Deendayal Garg

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

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(","));
    }
}

回答by Zergleb

in application.propertiesput

application.properties

endpoints.cors.allowed-origins=http://domain1.com,http://domain2.com,http://domain3.com

Spring Boot docs for properties

属性的 Spring Boot 文档

http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

回答by Stefan Isele - prefabware.com

This would not work, try instead :

这不起作用,请尝试:

registry.addMapping("/api/**")
        .allowedOrigins(
           "http://domain1.com",
           "http://domain2.com",
           "http://domain3.com")

see also spring reference cors

另见弹簧参考 cors

回答by Abhishek Ransingh

If you're using a Global CORS with Springboot and want to add multiple domains, this is how I've done it:

如果您在 Springboot 中使用 Global CORS 并想添加多个域,我就是这样做的:

In your property file, you can add your property and domains as below:

在您的属性文件中,您可以添加您的属性和域,如下所示:

allowed.origins=*.someurl.com,*.otherurl.com,*.someotherurl.com

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.

希望,这可以帮助您和其他正在寻找启用 Spring 的 CORS 的人。

回答by David

resources/application.yaml

资源/应用程序.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
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

配置/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

配置/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);
    }
}