当前位置: 首页 > news >正文

Spring Cloud Gateway 网关实现白名单功能

文章目录

      • 1 摘要
      • 2 核心 Maven 依赖
      • 3 白名单数据库设计
      • 4 核心代码
        • 4.1 白名单实体类
        • 4.2 白名单 DAO 接口
        • 4.3 初始化加载白名单
        • 4.4 权限过滤器
        • 4.5 白名单 Service 层
        • 4.6 白名单控制层
      • 5 Github 源码

1 摘要

对于微服务后台而言,网关层作为所有网络请求的入口。一般基于安全考虑,会在网关层做权限认证,但是对于一些例如登录、注册等接口以及一些资源数据,这些是不需要有认证信息,因此需要在网关层设计一个白名单的功能。本文将基于 Spring Cloud Gateway 2.X 实现白名单功能。

注意事项 : Gateway 网关层的白名单实现原理是在过滤器内判断请求地址是否符合白名单,如果通过则跳过当前过滤器。如果有多个过滤器,则需要在每一个过滤器里边添加白名单判断。

2 核心 Maven 依赖

./cloud-alibaba-gateway-filter/pom.xml
        <!-- cloud gateway -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
            <version>${spring-cloud-gateway.version}</version>
        </dependency>
        <!-- hutool -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>${hutool.version}</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
            <scope>runtime</scope>
        </dependency>
        <!-- Mybatis Plus(include Mybatis) -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>
        <!-- Redisson -->
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version>${redisson-spring.version}</version>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>


依赖对应的版本为:

        <lombok.version>1.18.24</lombok.version>
        <spring-cloud-gateway.version>2.2.5.RELEASE</spring-cloud-gateway.version>
        <servlet-api.version>4.0.1</servlet-api.version>
        <hutool.version>5.7.8</hutool.version>
        <mysql.version>8.0.27</mysql.version>
        <mybatis-plus.version>3.4.3.4</mybatis-plus.version>
        <redisson-spring.version>3.17.5</redisson-spring.version>

3 白名单数据库设计

./doc/sql/gateway-database-create.sql
/*==============================================================*/
/* Table: gateway_white_list                                    */
/*==============================================================*/
create table gateway_white_list
(
   id                   bigint unsigned not null comment 'id',
   route_type           varchar(32) comment '路由类型',
   path                 varchar(128) comment '请求路径',
   comment              varchar(128) comment '说明',
   create_date          bigint unsigned comment '创建时间',
   update_date          bigint unsigned comment '更新时间',
   primary key (id)
)
engine = innodb default
charset = utf8mb4;

alter table gateway_white_list comment '网关路由白名单';

4 核心代码

4.1 白名单实体类

./cloud-alibaba-gateway-filter/src/main/java/com/ljq/demo/springboot/alibaba/gateway/filter/model/WhiteListEntity.java
package com.ljq.demo.springboot.alibaba.gateway.filter.model;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

import java.io.Serializable;

/**
 * @Description: 网关路由白名单
 * @Author: junqiang.lu
 * @Date: 2022/8/23
 */
@Data
@TableName(value = "gateway_white_list")
public class WhiteListEntity implements Serializable {

    private static final long serialVersionUID = -854919732121208131L;

    /**
     * id
     */
    @TableId(type = IdType.NONE)
    private Long id;

    /**
     * 路由类型
     */
    private String routeType;

    /**
     * 请求路径
     */
    private String path;

    /**
     * 说明
     */
    private String comment;

    /**
     * 创建时间
     */
    private Long createDate;

    /**
     * 更新时间
     */
    private Long updateDate;

}

4.2 白名单 DAO 接口

./cloud-alibaba-gateway-filter/src/main/java/com/ljq/demo/springboot/alibaba/gateway/filter/dao/WhiteListMapper.java
package com.ljq.demo.springboot.alibaba.gateway.filter.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ljq.demo.springboot.alibaba.gateway.filter.model.WhiteListEntity;
import org.springframework.stereotype.Repository;

/**
 * @Description: 网关路由白名单DAO接口
 * @Author: junqiang.lu
 * @Date: 2022/8/23
 */
@Repository
public interface WhiteListMapper extends BaseMapper<WhiteListEntity> {


}

4.3 初始化加载白名单

./cloud-alibaba-gateway-filter/src/main/java/com/ljq/demo/springboot/alibaba/gateway/filter/common/component/WhiteListHandler.java
package com.ljq.demo.springboot.alibaba.gateway.filter.common.component;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ljq.demo.springboot.alibaba.gateway.filter.common.constant.RedisKeyConst;
import com.ljq.demo.springboot.alibaba.gateway.filter.dao.WhiteListMapper;
import com.ljq.demo.springboot.alibaba.gateway.filter.model.WhiteListEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 网关白名单处理类
 * @Author: junqiang.lu
 * @Date: 2022/8/23
 */
@Slf4j
@Component
public class WhiteListHandler implements ApplicationRunner {

    @Autowired
    private WhiteListMapper whiteListMapper;
    @Autowired
    private RedisComponent redisComponent;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 将所有白名单加载到缓存中
        log.info("-------------加载网关路由白名单------------------");
        List<WhiteListEntity> whiteListList = whiteListMapper.selectList(Wrappers.emptyWrapper());
        Map<String, Object> whiteListMap = new HashMap<>(16);
        whiteListList.forEach(whiteList -> whiteListMap.put(whiteList.getId().toString(), whiteList));
        redisComponent.mapPutBatch(RedisKeyConst.KEY_GATEWAY_WHITE_LIST, whiteListMap);
    }
}

4.4 权限过滤器

./cloud-alibaba-gateway-filter/src/main/java/com/ljq/demo/springboot/alibaba/gateway/filter/interceptor/AuthFilter.java
package com.ljq.demo.springboot.alibaba.gateway.filter.interceptor;

import cn.hutool.json.JSONUtil;
import com.ljq.demo.springboot.alibaba.gateway.filter.common.api.ApiResult;
import com.ljq.demo.springboot.alibaba.gateway.filter.common.component.RedisComponent;
import com.ljq.demo.springboot.alibaba.gateway.filter.common.constant.RedisKeyConst;
import com.ljq.demo.springboot.alibaba.gateway.filter.model.WhiteListEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

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

/**
 * @Description: 鉴权拦截器
 * @Author: junqiang.lu
 * @Date: 2020/12/8
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    private static final String TOKEN_KEY = "token";

    @Autowired
    private RedisComponent redisComponent;

    /**
     * 权限过滤
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String requestPath = exchange.getRequest().getPath().value();
        log.info("requestPath: {}",requestPath);
        // 判断是否符合白名单
        if (validateWhiteList(requestPath)) {
            return chain.filter(exchange);
        }
        List<String> tokenList = exchange.getRequest().getHeaders().get(TOKEN_KEY);
        log.info("token: {}", tokenList);
        if (CollectionUtils.isEmpty(tokenList) || tokenList.get(0).trim().isEmpty()) {
            ServerHttpResponse response = exchange.getResponse();
            // 错误信息
            byte[] data = JSONUtil.toJsonStr(ApiResult.fail("Token is null")).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(data);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            return response.writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }

    /**
     * 设置执行级别
     *
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }

    /**
     * 请求路径
     *
     * @param requestPath
     * @return
     */
    public boolean validateWhiteList(String requestPath) {
        List<WhiteListEntity> whiteListList = redisComponent.mapGetAll(RedisKeyConst.KEY_GATEWAY_WHITE_LIST,
                WhiteListEntity.class);
        for (WhiteListEntity whiteList : whiteListList) {
            if (requestPath.contains(whiteList.getPath()) || requestPath.matches(whiteList.getPath())) {
                return true;
            }
        }
        return false;
    }
}

必须在进入过滤器后首先进行白名单校验

白名单规则支持正则表达式

4.5 白名单 Service 层

Service 接口

./cloud-alibaba-gateway-filter/src/main/java/com/ljq/demo/springboot/alibaba/gateway/filter/service/WhiteListService.java
package com.ljq.demo.springboot.alibaba.gateway.filter.service;

import com.ljq.demo.springboot.alibaba.gateway.filter.common.api.ApiResult;
import com.ljq.demo.springboot.alibaba.gateway.filter.model.*;

/**
 * @Description: 白名单业务接口
 * @Author: junqiang.lu
 * @Date: 2022/8/23
 */
public interface WhiteListService {


    /**
     * 新增单条
     *
     * @param addParam
     * @return
     */
    ApiResult add(WhiteListAddParam addParam);

    /**
     * 查询单条
     *
     * @param infoParam
     * @return
     */
    ApiResult info(WhiteListInfoParam infoParam);

    /**
     * 分页查询
     *
     * @param pageParam
     * @return
     */
    ApiResult page(WhiteListPageParam pageParam);

    /**
     * 更新单条
     *
     * @param updateParam
     * @return
     */
    ApiResult update(WhiteListUpdateParam updateParam);

    /**
     * 删除单条
     *
     * @param deleteParam
     * @return
     */
    ApiResult delete(WhiteListDeleteParam deleteParam);

}

Service 业务实现类

./cloud-alibaba-gateway-filter/src/main/java/com/ljq/demo/springboot/alibaba/gateway/filter/service/impl/WhiteListServiceImpl.java
package com.ljq.demo.springboot.alibaba.gateway.filter.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljq.demo.springboot.alibaba.gateway.filter.common.api.ApiResult;
import com.ljq.demo.springboot.alibaba.gateway.filter.common.component.RedisComponent;
import com.ljq.demo.springboot.alibaba.gateway.filter.common.constant.RedisKeyConst;
import com.ljq.demo.springboot.alibaba.gateway.filter.dao.WhiteListMapper;
import com.ljq.demo.springboot.alibaba.gateway.filter.model.*;
import com.ljq.demo.springboot.alibaba.gateway.filter.service.WhiteListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @Description: 网关路由白名单业务实现类
 * @Author: junqiang.lu
 * @Date: 2022/8/23
 */
@Service
public class WhiteListServiceImpl extends ServiceImpl<WhiteListMapper, WhiteListEntity> implements WhiteListService {

    @Autowired
    private RedisComponent redisComponent;

    /**
     * 新增单条
     *
     * @param addParam
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public ApiResult add(WhiteListAddParam addParam) {
        WhiteListEntity whiteListParam = new WhiteListEntity();
        BeanUtil.copyProperties(addParam, whiteListParam, CopyOptions.create().ignoreError().ignoreNullValue());
        long nowTime = System.currentTimeMillis();
        whiteListParam.setCreateDate(nowTime);
        whiteListParam.setUpdateDate(nowTime);
        this.save(whiteListParam);
        redisComponent.mapPut(RedisKeyConst.KEY_GATEWAY_WHITE_LIST, whiteListParam.getId().toString(), whiteListParam);
        return ApiResult.success(whiteListParam);
    }

    /**
     * 查询单条
     *
     * @param infoParam
     * @return
     */
    @Override
    public ApiResult info(WhiteListInfoParam infoParam) {
        WhiteListEntity whiteList = redisComponent.mapGet(RedisKeyConst.KEY_GATEWAY_WHITE_LIST,
                infoParam.getId().toString(), WhiteListEntity.class);
        if (Objects.isNull(whiteList)) {
            whiteList = this.getById(infoParam.getId());
        }
        return ApiResult.success(whiteList);
    }

    /**
     * 分页查询
     *
     * @param pageParam
     * @return
     */
    @Override
    public ApiResult page(WhiteListPageParam pageParam) {
        IPage<WhiteListEntity> page = new Page<>(pageParam.getCurrentPage(), pageParam.getPageSize());
        LambdaQueryWrapper<WhiteListEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(StrUtil.isNotBlank(pageParam.getRouteType()), WhiteListEntity::getRouteType,
                        pageParam.getRouteType())
                .like(StrUtil.isNotBlank(pageParam.getPath()), WhiteListEntity::getPath, pageParam.getPath())
                .like(StrUtil.isNotBlank(pageParam.getComment()), WhiteListEntity::getComment, pageParam.getComment());
        return ApiResult.success(this.page(page, queryWrapper));
    }

    /**
     * 更新单条
     *
     * @param updateParam
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public ApiResult update(WhiteListUpdateParam updateParam) {
        WhiteListEntity whiteListParam = new WhiteListEntity();
        BeanUtil.copyProperties(updateParam, whiteListParam, CopyOptions.create().ignoreError().ignoreNullValue());
        long nowTime = System.currentTimeMillis();
        whiteListParam.setUpdateDate(nowTime);
        boolean flag = this.updateById(whiteListParam);
        if (flag) {
            redisComponent.mapPut(RedisKeyConst.KEY_GATEWAY_WHITE_LIST, whiteListParam.getId().toString(),
                    whiteListParam);
        }
        return ApiResult.success(flag);
    }

    /**
     * 删除单条
     *
     * @param deleteParam
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public ApiResult delete(WhiteListDeleteParam deleteParam) {
        boolean flag = this.removeById(deleteParam.getId());
        if (flag) {
            redisComponent.mapRemove(RedisKeyConst.KEY_GATEWAY_WHITE_LIST, deleteParam.getId().toString());
        }
        return ApiResult.success(flag);
    }
}

白名单的写操作都需要同步到缓存中

4.6 白名单控制层

./cloud-alibaba-gateway-filter/src/main/java/com/ljq/demo/springboot/alibaba/gateway/filter/controller/WhiteListController.java
package com.ljq.demo.springboot.alibaba.gateway.filter.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ljq.demo.springboot.alibaba.gateway.filter.common.api.ApiResult;
import com.ljq.demo.springboot.alibaba.gateway.filter.model.*;
import com.ljq.demo.springboot.alibaba.gateway.filter.service.WhiteListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Description: 网关路由白名单控制器
 * @Author: junqiang.lu
 * @Date: 2022/8/23
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/gateway/whitelist")
public class WhiteListController {

    @Autowired
    private WhiteListService whiteListService;

    /**
     * 新增白名单
     *
     * @param addParam
     * @return
     */
    @PostMapping(value = "/add", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<ApiResult<WhiteListEntity>> add(@RequestBody @Validated WhiteListAddParam addParam) {
        log.info("/add,新增白名单参数: {}", addParam);
        return ResponseEntity.ok(whiteListService.add(addParam));
    }

    /**
     * 查询单条白名单
     *
     * @param infoParam
     * @return
     */
    @GetMapping(value = "/info", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<ApiResult<WhiteListEntity>> info(@Validated WhiteListInfoParam infoParam) {
        log.info("/info,查询单条白名单参数: {}", infoParam);
        return ResponseEntity.ok(whiteListService.info(infoParam));
    }

    /**
     * 查询单条白名单
     *
     * @param pageParam
     * @return
     */
    @GetMapping(value = "/page", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<ApiResult<IPage<WhiteListEntity>>> page(@Validated WhiteListPageParam pageParam) {
        log.info("/page,分页查询白名单参数: {}", pageParam);
        return ResponseEntity.ok(whiteListService.page(pageParam));
    }

    /**
     * 修改白名单
     *
     * @param updateParam
     * @return
     */
    @PutMapping(value = "/update", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<ApiResult<Boolean>> update(@RequestBody @Validated WhiteListUpdateParam updateParam) {
        log.info("/update,修改白名单参数: {}", updateParam);
        return ResponseEntity.ok(whiteListService.update(updateParam));
    }

    /**
     * 删除单条白名单
     *
     * @param deleteParam
     * @return
     */
    @DeleteMapping(value = "/delete", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<ApiResult<Boolean>> delete(@RequestBody @Validated WhiteListDeleteParam deleteParam) {
        log.info("/delete,删除单条白名单参数: {}", deleteParam);
        return ResponseEntity.ok(whiteListService.delete(deleteParam));
    }
}

5 Github 源码

Gtihub 源码地址 : https://github.com/Flying9001/springBootDemo

相关文章:

  • Android Studio Chipmunk | 2021.2.1 Patch 2(2022 年 8 月)
  • 小程序商城上线需要做什么?
  • 选择边缘计算网关的五大优势
  • “蔚来杯“2022牛客暑期多校训练营4(A,D,H,K,N)
  • 达梦DataWatch主备环境搭建
  • python入门I--基本概念--基本语法--变量和标识符--数据类型
  • opencv-python之图像的加法与按位运算
  • rocketMq 安装
  • 明日风尚杂志明日风尚杂志社《明日风尚》杂志社2022年第10期目录
  • django之day01
  • Linux中bind9的view(视图解析)配置示例与注意事项
  • BEIT-3杂谈
  • Nuxt.js - 根据条件,动态控制页面是否缓存(keep-alive-props)
  • Linux/Ubuntu/Arm设备中通过/proc/stat等文件计算Cpu使用率
  • 面试精选:1、史上最详细的Nginx、LVS、HAProxy负载均衡精选面试题
  • Apache的80端口被占用以及访问时报错403
  • C++入门教程(10):for 语句
  • echarts的各种常用效果展示
  • ECMAScript6(0):ES6简明参考手册
  • Java的Interrupt与线程中断
  • mongodb--安装和初步使用教程
  • MySQL-事务管理(基础)
  • Node + FFmpeg 实现Canvas动画导出视频
  • python docx文档转html页面
  • Stream流与Lambda表达式(三) 静态工厂类Collectors
  • Vim 折腾记
  • 为物联网而生:高性能时间序列数据库HiTSDB商业化首发!
  • 学习使用ExpressJS 4.0中的新Router
  • 用Node EJS写一个爬虫脚本每天定时给心爱的她发一封暖心邮件
  • 掌握面试——弹出框的实现(一道题中包含布局/js设计模式)
  • Java数据解析之JSON
  • Java总结 - String - 这篇请使劲喷我
  • ​一文看懂数据清洗:缺失值、异常值和重复值的处理
  • # 20155222 2016-2017-2 《Java程序设计》第5周学习总结
  • # Swust 12th acm 邀请赛# [ E ] 01 String [题解]
  • #DBA杂记1
  • #Linux(帮助手册)
  • $分析了六十多年间100万字的政府工作报告,我看到了这样的变迁
  • (6)添加vue-cookie
  • (NSDate) 时间 (time )比较
  • (二)斐波那契Fabonacci函数
  • (附源码)计算机毕业设计SSM智慧停车系统
  • (算法)求1到1亿间的质数或素数
  • (一)Thymeleaf用法——Thymeleaf简介
  • (一)u-boot-nand.bin的下载
  • (转)EXC_BREAKPOINT僵尸错误
  • (转)项目管理杂谈-我所期望的新人
  • .bat批处理(五):遍历指定目录下资源文件并更新
  • .L0CK3D来袭:如何保护您的数据免受致命攻击
  • .NET 5种线程安全集合
  • .NET CLR基本术语
  • .Net Core webapi RestFul 统一接口数据返回格式
  • .NET HttpWebRequest、WebClient、HttpClient
  • .NET/C# 使窗口永不激活(No Activate 永不获得焦点)
  • .net连接MySQL的方法