欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

SpringCloud Gateway跨域配置代码实例

时间:2021-06-17 09:16:31|栏目:JAVA代码|点击:

这篇文章主要介绍了SpringCloud Gateway跨域配置代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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等中间件去做跨域的处理,业务服务就应该关注业务。

上一篇:java实现仿射密码加密解密

栏    目:JAVA代码

下一篇:JAVA读取HDFS的文件数据出现乱码的解决方案

本文标题:SpringCloud Gateway跨域配置代码实例

本文地址:http://www.codeinn.net/misctech/143179.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有