Spring Cloud Gateway + oauth2 跨域配置實現

JAVA_日月 發表於 2020-12-04

版本說明

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

再次編譯啟動專案,測試一波後,跨域配置成功生效

相關文章