springcloudgateway跨域及跨域配置不起作用

使用的是springcloud gateway遇到了跨域问题,配置了下面的跨域过滤器,不起作用。

package com.ph.crm.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class CorsOriginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (CorsUtils.isCorsRequest(request)) {
            ServerHttpResponse response = exchange.getResponse();
            HttpHeaders headers = response.getHeaders();
            headers.add("Access-Control-Allow-Origin", "*");
            headers.add("Access-Control-Allow-Methods", "*");
            headers.add("Access-Control-Max-Age", "18000L");
            headers.add("Access-Control-Allow-Headers", "*");
            headers.add("Access-Control-Expose-Headers", "*");
            headers.add("Access-Control-Allow-Credentials", "true");
            if (request.getMethod() == HttpMethod.OPTIONS) {
                response.setStatusCode(HttpStatus.OK);
                return Mono.empty();
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}

gateway使用的是webflux,而不是springmvc

修改为以下配置,跨域生效

package com.ph.crm.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@Configuration
public class RouteConfiguration {

    @Bean
    public WebFilter corsFilter() {
        return (ServerWebExchange ctx, WebFilterChain chain) -> {
            ServerHttpRequest request = ctx.getRequest();
            if (CorsUtils.isCorsRequest(request)) {
                ServerHttpResponse response = ctx.getResponse();
                HttpHeaders headers = response.getHeaders();
                headers.add("Access-Control-Allow-Origin", "*");
                headers.add("Access-Control-Allow-Methods", "*");
                headers.add("Access-Control-Max-Age", "18000L");
                headers.add("Access-Control-Allow-Headers", "*");
                headers.add("Access-Control-Expose-Headers", "*");
                headers.add("Access-Control-Allow-Credentials", "true");
                if (request.getMethod() == HttpMethod.OPTIONS) {
                    response.setStatusCode(HttpStatus.OK);
                    return Mono.empty();
                }
            }
            return chain.filter(ctx);
        };
    }
}

 

### 配置Spring Cloud Gateway中的CORS白名单 为了使Spring Cloud Gateway支持源资源共享(CORS),可以利用`CorsConfiguration`类来定义允许的来源、HTTP方法和其他必要的参数[^1]。通过创建一个全局过滤器或者针对特定路由设置CORS策略,能够有效地管理哪些外部名被授权访问API网关下的资源。 对于希望应用到整个系统的宽泛配置而言,在主应用程序类上添加如下@Bean定义即可实现: ```java import org.springframework.context.annotation.Bean; import org.springframework.web.cors.CorsConfiguration; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; // ... other imports ... @Configuration public class CorsConfig { @Bean public RouteLocator customRoutes(RouteLocatorBuilder builder) { String corsUrlPattern = "http://example.com"; // 替换成实际要加入白名单的URL模式 return builder.routes() .route(r -> r.path("/api/**") // 指定路径匹配规则 .filters(f -> f.addResponseHeader("Access-Control-Allow-Origin", corsUrlPattern)) .uri("lb://backend-service")) // 后端服务地址 .build(); } } ``` 上述代码片段展示了如何为指定路径下的请求添加响应头以允许来自给定模式(`corsUrlPattern`)的请求。需要注意的是,这种方式适用于简单的场景;如果需求更为复杂,则建议采用更灵活的方法——即基于`WebFilter`接口自定义逻辑处理每一个进入网关的HTTP请求,并动态决定是否放行该次调用[^2]。 此外,还可以直接修改application.yml文件内的属性来进行更加简便的操作: ```yaml spring: cloud: gateway: globalcors: add-to-simple-url-handler-mapping: true cors-configurations: '[/**]': allowedOrigins: "http://example.com" allowedMethods: - GET - POST - PUT - DELETE allowCredentials: true ``` 此YAML配置实现了相同的功能:它指定了允许越的所有原始站点以及它们可执行的动作列表。同时启用了凭证共享功能(`allowCredentials: true`),这通常用于涉及用户认证信息交换的情况中[^3]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值