码迷,mamicode.com
首页 > 编程语言 > 详细

SpringCloud Gateway跨域配置

时间:2019-11-21 13:41:29      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:pos   关注   auto   ref   code   url   mod   中间件   response   

Springboot版本:2.1.8.RELEASE

SpringCloud版本:Greenwich.SR2

yml配置:

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          [/**]: 
            # 允许携带认证信息
            # 允许跨域的源(网站域名/ip),设置*为全部
            # 允许跨域请求里的head字段,设置*为全部
            # 允许跨域的method, 默认为GET和OPTIONS,设置*为全部
            # 跨域允许的有效期
            allow-credentials: true
            allowed-origins: 
            - "http://localhost:13009"
            - "http://localhost:13010"
            allowed-headers: "*"
            allowed-methods: 
            - OPTIONS
            - GET
            - POST
            max-age: 3600
            # 允许response的head信息
            # 默认仅允许如下6个:
            #     Cache-Control
            #     Content-Language
            #     Content-Type
            #     Expires
            #     Last-Modified
            #     Pragma
            #exposed-headers:

配置类:org.springframework.cloud.gateway.config.GlobalCorsProperties

网上有很多人说这样配无效,但我测试下来是OK的,如果真的无效,可以手动去装配Cros配置:

 package com.longge.gateway.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.cloud.gateway.config.GlobalCorsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * @author roger yang
 * @date 11/21/2019
 */
@Configuration
@ConditionalOnBean(GlobalCorsProperties.class)
public class CorsAutoConfiguration {
    @Autowired
    private  GlobalCorsProperties globalCorsProperties;
    
    @Bean
    public CorsWebFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        globalCorsProperties.getCorsConfigurations().forEach((path,corsConfiguration)->source.registerCorsConfiguration(path, corsConfiguration));
        return new CorsWebFilter(source);
    }
}

 

当然,我们更推荐在Nginx等中间件去做跨域的处理,业务服务就应该关注业务。

Nginx配置跨域可以参考我的另外一篇Blog:https://www.cnblogs.com/yangzhilong/p/9230778.html

SpringCloud Gateway跨域配置

标签:pos   关注   auto   ref   code   url   mod   中间件   response   

原文地址:https://www.cnblogs.com/yangzhilong/p/11905007.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!