美文网首页
gateway网关拦截

gateway网关拦截

作者: 半日孤独 | 来源:发表于2020-09-08 11:37 被阅读0次

    实现 GlobalFilter, Ordered

    @Component
    @Slf4j
    public class MyGateWayFilter implements GlobalFilter, Ordered {
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            ServerHttpRequest request = exchange.getRequest();
            String token = request.getHeaders().getFirst("X-token");
            if (("/api/login").equals(request.getURI().getPath())) {
                //登录接口,通过
                return chain.filter(exchange);
            }
            // 如果请求头不存在 Token
            if (token == null) {
                return this.getResponseError(exchange, "token不能为空,请重新登录");
            }
           return chain.filter(exchange);
        }
        @Override
        public int getOrder() {
            return 0;
        }
    

    拦截失败自定义返回错误信息

        private Mono<Void> getResponseError(ServerWebExchange exchange, String msg) {
            ServerHttpResponse response = exchange.getResponse();
            JSONObject message = new JSONObject();
            message.put("code", -1);
            message.put("message", msg);
            byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //指定编码,否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
    

    getOrder

    此方法代表拦截优先级,数字越低,优先级越高。

    相关文章

      网友评论

          本文标题:gateway网关拦截

          本文链接:https://www.haomeiwen.com/subject/awudektx.html