IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Spring Cloud Gateway 网关实现白名单功能 -> 正文阅读

[Java知识库]Spring Cloud Gateway 网关实现白名单功能

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

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-09-04 00:56:31  更:2022-09-04 01:01:12 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 13:08:49-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码