网关解决跨域问题

创建配置类

@Configuration
public class CorsConfig {@Beanpublic CorsWebFilter corsFilter() {CorsConfiguration config = new CorsConfiguration();config.addAllowedMethod("*");config.addAllowedOrigin("*");config.addAllowedHeader("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());source.registerCorsConfiguration("/**", config);return new CorsWebFilter(source);}
}

全局Filter,统一处理会员登录与外部不允许访问的服务

import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;import java.nio.charset.StandardCharsets;
import java.util.List;/*** <p>* 全局Filter,统一处理会员登录与外部不允许访问的服务* </p>*/
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {private AntPathMatcher antPathMatcher = new AntPathMatcher();@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {ServerHttpRequest request = exchange.getRequest();String path = request.getURI().getPath();//谷粒学院api接口,校验用户必须登录if(antPathMatcher.match("/api/**/auth/**", path)) {List<String> tokenList = request.getHeaders().get("token");if(null == tokenList) {ServerHttpResponse response = exchange.getResponse();return out(response);} else {
//                Boolean isCheck = JwtUtils.checkToken(tokenList.get(0));
//                if(!isCheck) {ServerHttpResponse response = exchange.getResponse();return out(response);
//                }}}//内部服务接口,不允许外部访问if(antPathMatcher.match("/**/inner/**", path)) {ServerHttpResponse response = exchange.getResponse();return out(response);}return chain.filter(exchange);}@Overridepublic int getOrder() {return 0;}private Mono<Void> out(ServerHttpResponse response) {JsonObject message = new JsonObject();message.addProperty("success", false);message.addProperty("code", 28004);message.addProperty("data", "鉴权失败");byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);DataBuffer buffer = response.bufferFactory().wrap(bits);//response.setStatusCode(HttpStatus.UNAUTHORIZED);//指定编码,否则在浏览器中会中文乱码response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");return response.writeWith(Mono.just(buffer));}
}

自定义异常处理

服务网关调用服务时可能会有一些异常或服务不可用,它返回错误信息不友好,需要我们覆盖处理

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
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.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;import java.util.Collections;
import java.util.List;/*** 覆盖默认的异常处理**/
@Configuration
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class ErrorHandlerConfig {private final ServerProperties serverProperties;private final ApplicationContext applicationContext;private final ResourceProperties resourceProperties;private final List<ViewResolver> viewResolvers;private final ServerCodecConfigurer serverCodecConfigurer;public ErrorHandlerConfig(ServerProperties serverProperties,ResourceProperties resourceProperties,ObjectProvider<List<ViewResolver>> viewResolversProvider,ServerCodecConfigurer serverCodecConfigurer,ApplicationContext applicationContext) {this.serverProperties = serverProperties;this.applicationContext = applicationContext;this.resourceProperties = resourceProperties;this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);this.serverCodecConfigurer = serverCodecConfigurer;}@Bean@Order(Ordered.HIGHEST_PRECEDENCE)public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {JsonExceptionHandler exceptionHandler = new JsonExceptionHandler(errorAttributes,this.resourceProperties,this.serverProperties.getError(),this.applicationContext);exceptionHandler.setViewResolvers(this.viewResolvers);exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());return exceptionHandler;}
}
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;import java.util.HashMap;
import java.util.Map;/*** 自定义异常处理** <p>异常时用JSON代替HTML异常信息<p>**/
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,ErrorProperties errorProperties, ApplicationContext applicationContext) {super(errorAttributes, resourceProperties, errorProperties, applicationContext);}/*** 获取异常属性*/@Overrideprotected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {Map<String, Object> map = new HashMap<>();map.put("success", false);map.put("code", 20005);map.put("message", "网关失败");map.put("data", null);return map;}/*** 指定响应处理方法为JSON处理的方法* @param errorAttributes*/@Overrideprotected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);}/*** 根据code获取对应的HttpStatus* @param errorAttributes*/@Overrideprotected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {return HttpStatus.OK;}
}

SpringCloud(Gateway网关跨域)相关推荐

  1. gateway网关跨域的配置

    第一种方法在网关服务里增加config,详细代码如下. import org.springframework.context.annotation.Bean; import org.springfra ...

  2. 访问接口一直在报401问题Springboot和spring cloud gateway的跨域问题

    最近在帮忙联调一个项目的接口,架构是别人搭建的,我只是帮忙联调业务. 打开之后发现昨天还好好的项目,现在调试起来全报401,因为是SpringCloud项目,zuul换成了gateway,因为gate ...

  3. SpringCloud系列教程(五)之SpringCloud Gateway 网关聚合开发文档 swagger knife4j 和登录权限统一验证【Hoxton版】

    阅读提醒: 本文面向的是有一定springboot基础者 本次教程使用的Spring Cloud Hoxton RELEASE版本 由于knife4j比swagger更加友好,所以本文集成knife4 ...

  4. 网关gateway解决跨域问题

    Gateway 前言 API 网关出现的原因是微服务架构的出现,不同的微服务一般会有不同的网络地址,而外部客户端可能需要调用多个服务的接口才能完成一个业务需求,如果让客户端直接与各个微服务通信,会有以 ...

  5. 网关 跨域_好文推荐:微服务网关实战—Spring Cloud Gateway

    作者:博云BoCloud| 前言 作为Netflix Zuul的替代者,Spring Cloud Gateway是一款非常实用的微服务网关,在Spring Cloud微服务架构体系中发挥非常大的作用. ...

  6. Spring Cloud Gateway 解决跨域问题

      注:文中的解决方案在 Spring Cloud 2021.0.4.Spring Boot 2.7.4 版本中得到验证,完美解决,其他版本可参考   请求流程如下图:通过nginx反向代理到网关,在 ...

  7. gateway配置跨域

    什么是跨域 浏览器同源策略:协议.域名.端口完全一致,则符合同源策略. 不符合同源策略,就会产生跨域问题. 跨域解决方案 通过jsonp跨域 document.domain + iframe跨域 lo ...

  8. Gateway 实现跨域

    一. 跨域概念 跨源资源共享(CORS)详情概念: 跨源资源共享(CORS) - HTTP | MDN 解释 跨域首先会发送一个 预检请求,OPTIONS,去问服务器能不能跨域服务器告诉他能跨域,就可 ...

  9. When allowCredentials is true, allowedOrigins cannot contain the specia 跨域 网关跨域

    解决办法:跨域配置报错,将.allowedOrigins替换成.allowedOriginPatterns即可. SpringBoot2.0.0中 @Configuration public clas ...

最新文章

  1. 20180517早课记录12-Hadoop
  2. 转 使用 HttpClient 4 进行文件上传
  3. 【pytorch学习】四种钩子方法(register_forward_hook等)的用法和注意点
  4. Timer和TimerTask类 例子 .
  5. IOS15之优雅的使用UITableView
  6. 阿里巴巴指东打西,PC之后卖盒饭?
  7. mysql无法添加或更新子行_违反完整性约束:1452无法添加或更新子行:
  8. 【嵌入式Linux】嵌入式Linux驱动开发基础知识之设备树模型
  9. 用qt调用第三方库resolve
  10. 转:Python yield 使用浅析
  11. dx 汇编dec_汇编语言算术指令
  12. 弹幕有硬伤,转变主流成妄想
  13. linux 文件管理器,linux终端文件管理器ranger使用详解
  14. 送给正在 奋斗和成长路上的女人们
  15. 小程序组件-仿微信通讯录
  16. 【附源码】计算机毕业设计JAVA医院远程诊断系统
  17. 数字大小写转换:如何把“0123456789”转换成“零一二三四五六七八九”?
  18. 【论文分享】★★★「SOTA」小样本图神经网络分类模型 HGNN:Hybrid Graph Neural Networks for Few-Shot Learning
  19. python bokeh_使用 Bokeh 为你的 Python 绘图添加交互性
  20. 带你轻松把握实行DB2的饬令

热门文章

  1. java-多线程安全-锁
  2. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-008排序算法的复杂度(比较次数的上下限)...
  3. 获得md5加密后的字符串
  4. 数字图像处理之边缘检测,图像分割
  5. 登陆时不显示上一次登陆的用户名
  6. android nfc(一)
  7. mysql left join 结果怎么这么慢
  8. 个人对持续集成的理解和实践
  9. 用ArrayList作数据源为ComboBox绑定,带“请选择...”
  10. 编辑器FreeTextBox升级至3.0