欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring-Cloud网关API 过滤器实现

程序员文章站 2022-05-23 08:38:16
...
  • 项目结构:Spring-Cloud网关API 过滤器实现
  • 源码:
package com.server.mygetway.route;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Properties;

@Component
public class ApiGlobalFilter implements GlobalFilter {
    //简单实现
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取token
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        //通过判断 是否有token
        if (StringUtils.isBlank(token)) {
            ServerHttpResponse response = exchange.getResponse();
            Properties properties = new Properties();
            properties.put("status", -1);
            properties.put("data", "鉴权失败");

            byte[] bit = properties.toString().getBytes(StandardCharsets.UTF_8);

            DataBuffer dataBuffer = response.bufferFactory().wrap(bit);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "text/json;charset=UTF-8");
            return response.writeWith(Mono.just(dataBuffer));
        }
        //通过
        return chain.filter(exchange);
    }
    //通过网关访问 网关ip/网关端口/服务名称/接口
    //访问http://127.0.0.1:9090/KAFKA/getMap
    //访问http://127.0.0.1:9090/KAFKA/getMap?token=123
}