gateway网关拦截

2020-09-08  本文已影响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

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

猜你喜欢

热点阅读