spring cloud gateway 全局token校验

全局token校验,代码如下


@Component
public class TokenGlobalFilter implements GlobalFilter, Ordered {

    /**
     * 不进行token校验的请求地址 可配置在配置文件中
     */
    @Value("#{'${ignoreUrlList}'.split(',')}")
    public List<String> ignoreUrlList;

    /**
     * 拦截所有的请求头
     * 
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求url
        String requestUrl = request.getPath().toString();
        Boolean canSkip = false;

        // 请求方式是OPTIONS的时候 跳过
        String method = request.getMethod().name();
        if (RequestMethod.OPTIONS.name().equals(method)) {
            canSkip = true;
        }
        if (!canSkip) {
            // 是否是不进行token校验的请求地址
            canSkip = !ignoreUrlList.parallelStream().filter(x -> requestUrl.contains(x)).collect(Collectors.toList())
                    .isEmpty();
        }
        if (canSkip) {
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst(Token);
        if (StringUtils.isBlank(token)) {
            JSONObject message = new JSONObject();
            message.put("code", 401);
            message.put("message", "无token");
            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));
        }
        LoginResult currentUser = this.getLoginResultByToken(token);
        if (currentUser == null || currentUser.getData() == null || !currentUser.isSuccess()) {
            JSONObject message = new JSONObject();
            message.put("code", 401);
            message.put("message", "无效token");
            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));
        }
        // 将用户信息放到header中
        String userInfo = "";
        try {
            // 为防止中文乱码 先编码
            userInfo = URLEncoder.encode(JSON.toJSONString(currentUser), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ServerHttpRequest mutableReq = exchange.getRequest().mutate().header("userInfo", userInfo).build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
        return chain.filter(mutableExchange);

    }

    /**
     * 根据token获取用户信息
     * 
     * @param token
     * @return LoginResult
     */
    private LoginResult getLoginResultByToken(String token) {
        // 根据token获取用户信息
    }

    @Override
    public int getOrder() {
        return -200;
    }
}

你可能感兴趣的:(spring,cloud,java)