版本说明
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);
}
}
再次编译启动项目,测试一波后,跨域配置成功生效