【问题标题】:add multiple cross origin urls in spring boot在 Spring Boot 中添加多个跨源 URL
【发布时间】:2017-01-30 02:19:44
【问题描述】:

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

【问题讨论】:

标签: spring spring-mvc spring-boot cors


【解决方案1】:

这不行,试试吧:

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

另见spring reference cors

【讨论】:

  • 如何在此处传递域列表而不是硬编码?
  • @brainstorm 只需声明一个字符串数组 (String[] originArray = new Array[] {"domain1.com", "domain2.com", "domain3.com"}) 并将其传递给.allowedOrigins-方法 (...allowedOrigins(originArray) )。
【解决方案2】:

您设置的方式只会设置第三个原点,其他两个将消失。

如果您想设置所有三个来源,则需要将它们作为逗号分隔的字符串传递。

@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

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

【讨论】:

  • 可以从属性文件中读取这些域吗?即我注入值并将它们传递给.allowedOrigins ?
  • 或者有没有办法通过列表?
  • 当然。可以做到。更新了答案。也可能有其他方法。那是一种方式。假设您的类路径中有一个 config.properties 文件,并且该文件有一个键名来源,其值由 Comma 分隔
  • 传递列表是不可能的,因为allowedOrigins 将数组作为输入。
  • 我可以简单地传递数组而不是列表吗?
【解决方案3】:

在 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

【讨论】:

    【解决方案4】:

    如果您在 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 的人有所帮助。

    【讨论】:

    • 我不相信这将在子域级别使用通配符起作用 - 换句话说,您的 allowed.origins 列表应该是确切的域。
    【解决方案5】:

    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】:

      创建您的自定义注释并使用它注释 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
      }
      

      对我来说工作得很好。!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 2019-10-09
        • 1970-01-01
        • 1970-01-01
        • 2018-01-24
        • 1970-01-01
        • 2023-02-22
        相关资源
        最近更新 更多