springcloud gateway + oauth2引起的跨

2021-07-23  本文已影响0人  lgtn

项目技术架构:
前端:vue
后端:springcloud h版
1、网关:gateway
( 1)作为所有资源的统一访问入口,需要支持跨域
(2)依赖oauth2,使用resource相关api,同时作为资源服务器,进行权限认证

当写好接口后,本机使用postman测试,接口都正常返回,但配合前端测试时,一直出现下面两个问题,而前端使用proxy代理,也仍然无法解决。

问题一:
访问XMLHttpRequest at'http://ip:port/randCodeImage?_method=get'来源'http://localhost:8081'已被CORS策略阻止:'Access Control Allow Origin'标头包含多个值“”,但只允许一个值。

问题二:
Access to XMLHttpRequest at 'http://ip:port/userInfo' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

最初解决办法

1、配置yml,针对问题一,查阅相关资料后,可以只保留一个。问题一可以解决

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            # 允许携带认证信息
            allow-credentials: true
            # 允许跨域的源(网站域名/ip),设置*为全部
            allowedOrigins: "*"
            # 允许跨域的method, 默认为GET和OPTIONS,设置*为全部
            allowedMethods: "*"
            # 允许跨域请求里的head字段,设置*为全部
            allowedHeaders: "*"
      default-filters:
      #相同header多个值时的处理方式,三种规则可选(RETAIN_FIRST|RETAIN_UNIQUE|RETAIN_LAST)
        - DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentials, RETAIN_FIRST
DedupeResponseHeader的源码见:org.springframework.cloud.gateway.filter.factory.DedupeResponseHeaderGatewayFilterFactory

但问题二,不论是自己写跨域过滤器,还是调整yml的配置,都得不到解决。百思不得其解。

最终解决办法:关掉ResourceServerConfig的跨域配置,并且引入自定义的跨域过滤器

1、百度后,有人说要关掉weblfux的跨域,但不知道如何关。
2、后来发现,浏览器在发起options 探测请求时,一直被网关阻止,出现了401错误,怀疑可能是oauth2引起的。结合1中的提法,尝试引入oauth2的跨域配置,引入自定义跨域过滤器,问题二得到解决。

关键代码:

// 引入跨域
        http.cors().and().csrf().disable();
      // 增加自定义拦截器
        http.addFilterAt(new CorsFilter(), SecurityWebFiltersOrder.SECURITY_CONTEXT_SERVER_WEB_EXCHANGE);

附最终代码:

SecurityWebFilterChain配置

 @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        // 关掉跨域
        http.cors().and().csrf().disable();
      // 增加自定义拦截器
        http.addFilterAt(new CorsFilter(), SecurityWebFiltersOrder.SECURITY_CONTEXT_SERVER_WEB_EXCHANGE);
        http.oauth2ResourceServer().jwt()
                .jwtAuthenticationConverter(jwtAuthenticationConverter());
        // 如果是token过期了,需要加到oauth2ResourceServer上,才会起作用,下面不知道为什么不起作用
        http.oauth2ResourceServer().authenticationEntryPoint(restAuthenticationEntryPoint);
        http.authorizeExchange()
                .pathMatchers(ArrayUtil.toArray(ignoreUrlsConfig.getUrls(), String.class)).permitAll()//白名单配置
                .pathMatchers("/login", "/new/login", "/webjars/**",
                        "/js/**", "/config/**", "/images/**", "/css/**", "/commonlib/**", "/thirdlibs/**",
                        "/favicon.ico", "/loginServer/**", "/randCodeImage/**",
                        "/oauth/**", "*.js", "/**/*.json", "/**/*.css", "/**/*.js", "/portal/**", "/**/*.map", "/**/*.html",
                        "/**/*.png", "uum/region/enum/**").permitAll()
                .anyExchange().access(authorizationManager)//鉴权管理器配置
                .and().exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)//处理未授权
                .authenticationEntryPoint(restAuthenticationEntryPoint)//处理未认证
                .and().headers().frameOptions().disable() //允许iframe
        ;

        return http.build();
    }

CorsFilter定义:

@Configuration
public class CorsFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange ctx, WebFilterChain chain) {
        ServerHttpRequest request = ctx.getRequest();
        if (CorsUtils.isCorsRequest(request)) {
            ServerHttpResponse response = ctx.getResponse();
            HttpHeaders headers = response.getHeaders();
            headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "");
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "false");
            headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
            headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600");
            if (request.getMethod() == HttpMethod.OPTIONS) {
                response.setStatusCode(HttpStatus.OK);
                return Mono.empty();
            }
        }
        return chain.filter(ctx);
    }
}

上一篇下一篇

猜你喜欢

热点阅读