在Spring Boot中添加多个跨源URL [英] add multiple cross origin urls in spring boot

查看:514
本文介绍了在Spring Boot中添加多个跨源URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一个有关如何在spring-boot应用程序中设置cors标头的示例.由于我们有很多起源,所以我需要添加它们.以下有效吗?

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?

@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".

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.

编辑:最理想的用例是注入一个域列表(来自application.properties),并在allowedOrigins中进行设置.有可能

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

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

推荐答案

您设置的方式只会设置第三个原点,而另外两个会消失.

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:

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

这篇关于在Spring Boot中添加多个跨源URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆