spring cloud ouath2 +getway跨域是有特别的配置的(与普通跨域不同)
1.bootstrap.yml
spring: cloud: gateway: globalcors: add-to-simple-url-handler-mapping: true corsConfigurations: '[/**]': # 支持跨域访问的来源 也就是前台地址 可以配置多个 方法如下 allowedOrigins: - "http://192.168.xx.xx:8080" - "http://192.168.xx.xx:8080" # 切记 allowCredentials 配置 为true时,allowedOrigins不能为 * allowCredentials: true maxAge: 86400 # 支持的方法 * 代表所有 allowedMethods: "*" allowedHeaders: "*" exposedHeaders: "setToken" routes: # 路由标识(id:标识,具有唯一性) 截取请求 - id: auth # 目标服务地址(uri:地址,请求转发后的地址) uri: lb://auth # 路由条件(predicates:断言,匹配 HTTP 请求内容) predicates: ## 转发地址格式为 uri/archive,/str 部分会被下面的过滤器给截取掉 - Path=/auth/**
GatewayConfig
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 GatewayConfig { /** * 配置全局解决cors跨域问题 * * @return */ @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); } }