Spring MVC 在spring Boot 中添加多个交叉源url

pu82cl6c  于 2022-11-14  发布在  Spring
关注(0)|答案(7)|浏览(196)

我找到了一个关于如何在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“设置。

EDIT:的理想用例是插入域列表(来自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)
    }
}
oknwwptz

oknwwptz1#

在Sping 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
wlp8pajw

wlp8pajw2#

你设置的方式只会设置第三个原点,其他两个原点都会消失。
如果你想设置所有三个原点,那么你需要将它们作为逗号分隔的字符串来传递。

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

bvk5enib3#

此操作无效,请尝试:

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

另请参阅spring reference cors

yk9xbfzb

yk9xbfzb4#

如果您正在使用带有Springboot的Global CORS,并且希望添加多个域,我是这样做的:
在属性文件中,可以按如下方式添加属性和域:
allowed.origins=*.someurl.com,*.otherurl.com,*.someotherurl.com
以及您的Config类:

@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的人有帮助。

kdfy810k

kdfy810k5#

创建自定义注解并使用该注解对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
}

对我来说非常好!!

cgyqldqp

cgyqldqp6#

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

vbkedwbf7#

这对使用Springboot 2.7.0的我很有效

应用程序.yml

allowedOrigins: http://localhost:[*], http://*.your-domain.com:[*]

相关配置

@Configuration
public class CorsConfig {

@Value("${allowedOrigins}")
private List<String> domains;

@Bean
public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean(){
          UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
          CorsConfiguration config = new CorsConfiguration();
          
          // very important to allow patterns !!!
          config.setAllowedOriginPatterns(domains);

          source.registerCorsConfiguration("/**", config); 
          .....
          return new FilterRegistrationBean<>(new CorsFilter(source));
}

相关问题