springcloud-gateway CorsWebFilter CORS跨域配置无效

先说结论:如果要跨域发送Cookie,Access-Control-Allow-Origin就不能设为星号

config.setAllowCredentials(true)

config.addAllowedOrigin("*")

config.addAllowedOrigin("*")-----换成-->config.addAllowedOriginPattern("*")

或者你不需要跨域发送Cookie,可以改为false。

原因:

1.首先理解Cookie。百度解释就够了 百度搜索Cookie

   Cookie作用就是保存用户信息在本地,用户每次访问站点时,Web应用程序都可以读取 Cookie 包含的信息。当用户再次访问这个站点时,浏览器就会在本地硬盘上查找与该 URL 相关联Cookie。如果该 Cookie 存在,浏览器就将它添加到request headerCookie字段中,与http请求一起发送到该站点。

Cookie遵循同源策略,它的组成中

domain 和 path 这两个选项共同决定了Cookie能被哪些页面共享

        (3)Path属性:定义了Web站点上可以访问该Cookie的目录

        (4)Domain属性:指定了可以访问该 Cookie 的 Web 站点或域

简单来说就是,我们网页登录了腾讯视频,关闭后,一段时间内都不用重新登录,但是你不能说你现在要看爱奇艺了也不用登录,哪怕是同样的账号密码,怎么区分的呢,因为你进爱奇艺时是读取不到 Domain和Path是腾讯视频的Cookie信息的。

所以这个地址是保证Cookie使用和安全很重要的凭证。因此Cookie默认是不能跨域的。

2.理解跨域请求。可以看这篇文章跨域资源共享 CORS 详解 - 阮一峰的网络日志 

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。

它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

但是我们就是要跨域发送Cookie,那他就规定了,你要跨域发送Cookie,allowedOrigins就不能设为星号,而allowedOriginPatterns没有这个validate验证。

spring-web5.3.1 CorsConfiguration源码。 老一些的版本没有这个报错。

    @Nullable
    public String checkOrigin(@Nullable String origin) {
        if (!StringUtils.hasText(origin)) {
            return null;
        } else {
            String originToCheck = this.trimTrailingSlash(origin);
            Iterator var3;
            if (!ObjectUtils.isEmpty(this.allowedOrigins)) {
                if (this.allowedOrigins.contains("*")) {
                    this.validateAllowCredentials();
                    return "*";
                }

                var3 = this.allowedOrigins.iterator();

                while(var3.hasNext()) {
                    String allowedOrigin = (String)var3.next();
                    if (originToCheck.equalsIgnoreCase(allowedOrigin)) {
                        return origin;
                    }
                }
            }

            if (!ObjectUtils.isEmpty(this.allowedOriginPatterns)) {
                var3 = this.allowedOriginPatterns.iterator();

                while(var3.hasNext()) {
                    CorsConfiguration.OriginPattern p = (CorsConfiguration.OriginPattern)var3.next();
                    if (p.getDeclaredPattern().equals("*") || p.getPattern().matcher(originToCheck).matches()) {
                        return origin;
                    }
                }
            }

            return null;
        }
    }
    public void validateAllowCredentials() {
        if (this.allowCredentials == Boolean.TRUE && this.allowedOrigins != null && this.allowedOrigins.contains("*")) {
            throw new IllegalArgumentException("When allowCredentials is true, allowedOrigins cannot contain the special value \"*\" since that cannot be set on the \"Access-Control-Allow-Origin\" response header. To allow credentials to a set of origins, list them explicitly or consider using \"allowedOriginPatterns\" instead.");
        }
    }
Spring Cloud Gateway配置CORS跨域资源共享),您可以按照以下步骤进行: 1. 首先,添加一个全局的CorsGlobalFilter Bean,用于处理CORS跨域请求。创建一个新的类文件,比如CustomCorsGlobalFilter: ```java import org.springframework.boot.web.reactive.filter.OrderedCorsFilter; import org.springframework.core.Ordered; 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.stereotype.Component; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsUtils; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import reactor.core.publisher.Mono; @Component public class CustomCorsGlobalFilter implements WebFilter, Ordered { private static final String ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN"; private static final String ALLOWED_METHODS = "GET, PUT, POST, DELETE, OPTIONS"; private static final String ALLOWED_ORIGIN = "*"; private static final String ALLOWED_EXPOSE = "Authorization"; @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); if (CorsUtils.isCorsRequest(request)) { ServerHttpResponse response = exchange.getResponse(); HttpHeaders headers = response.getHeaders(); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ALLOWED_ORIGIN); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, ALLOWED_HEADERS); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, ALLOWED_METHODS); headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALLOWED_EXPOSE); headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600"); if (request.getMethod() == HttpMethod.OPTIONS) { response.setStatusCode(HttpStatus.OK); return Mono.empty(); } } return chain.filter(exchange); } @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } } ``` 2. 然后,您需要将这个Filter注册到Spring Boot应用程序中。在您的Spring Boot主类中,添加`@EnableWebFlux`注解,并且创建一个名为`customCorsFilter`的Bean: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.reactive.config.EnableWebFlux; @SpringBootApplication @EnableWebFlux public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } @Bean public CustomCorsGlobalFilter customCorsFilter() { return new CustomCorsGlobalFilter(); } } ``` 3. 最后,您可以在application.properties(或application.yml)文件中配置其他CORS属性,例如允许的源和方法: ```properties spring: cloud: gateway: globalcors: corsConfigurations: '[/**]': allowedOrigins: "*" allowedMethods: "GET, PUT, POST, DELETE, OPTIONS" allowedHeaders: "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN" exposedHeaders: "Authorization" maxAge: 3600 ``` 注意:以上只是一个示例配置,您可以根据您的实际需求进行调整。 这样,您就成功地配置Spring Cloud GatewayCORS支持。请记住,CORS是一个安全特性,您应该根据您的应用程序需求和安全性要求进行适当的配置
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值