Spring Cloud Gateway + oauth2 跨域配置实现

版本说明

spring-cloud-starter-gateway : 2.2.5RELEASE
spring-cloud-starter-oauth2 : 2.2.4RELEASE
spring-security-oauth2 : 2.3.8RELEASE

nacos跨域配置

spring:
  cloud:
    gateway:      
      globalcors:
        add-to-simple-url-handler-mapping: true        
        corsConfigurations:
          '[/**]': 
          	# 支持跨域访问的来源
            allowedOrigins: 
              - "http://localhost:8080"
            # 切记 allowCredentials 配置 为true时,allowedOrigins不能为 * 
            allowCredentials: true
            # 浏览器跨域嗅探间隔 单位秒
            maxAge: 86400
            # 支持的方法 * 代表所有
            allowedMethods: "*"
            allowedHeaders: "*"
            exposedHeaders: "setToken"

网上搜了一堆,大多都是上面的这些,但是如果只进行这样的配置的话,根本不会生效,我这边的gateway是集成了oauth2进行鉴权的,最后在Spring Security官方文档上看到了这一段
https://docs.spring.io/spring-security/site/docs/current/reference/html5/#cors
在这里插入图片描述
琢磨一番加参考其他博客之后。。。

gateway添加跨域配置类

CorsConfig.java

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.config.GlobalCorsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;


@Configuration
@EnableConfigurationProperties(GlobalCorsProperties.class)
public class CorsConfig {

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @RefreshScope
    @Bean
    public CorsWebFilter corsWebFilter(GlobalCorsProperties globalCorsProperties){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        globalCorsProperties.getCorsConfigurations().forEach((k,v) -> source.registerCorsConfiguration(k, v));
        return new CorsWebFilter(source);
    }
}

再次编译启动项目,测试一波后,跨域配置成功生效

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值