add multiple cross origin urls in spring boot

前端 未结 6 1293
太阳男子
太阳男子 2021-02-02 13:50

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
         


        
6条回答
  •  忘了有多久
    2021-02-02 13:59

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

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

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

提交回复
热议问题