springBoot实现返回日志脱敏

2024/8/13 加密

# 1、简介

secure-ext-spring-boot-starter (opens new window)专注安全领域,实现内容脱敏展示,期望做到可灵活配置,灵活启用,并且最好内置丰富插件,支持手机号、邮箱、身份证号、住址、中文名、座机号、银行卡、自定义等多种类型的脱敏配置。

# 2、优点

易集成: 只需引入starter包,简单到无需任何初始化配置;

灵活: 具体到方法级;

内置丰富: 内置多种默认类型,且可根据自身需求,支持自定义脱敏规则

自动化: 支持深度脱敏,自动寻找返回值中嵌套对象包含的需脱敏的属性

# 3、最新版本

Maven Central (opens new window)

# 4、使用步骤

# 4.1 引入依赖

<dependency>
  <groupId>io.gitee.chemors</groupId>
  <artifactId>secure-ext-spring-boot-starter</artifactId>
  <version>Lastest Version</version>
</dependency>
1
2
3
4
5

# 4.2 开启脱敏注解

sensitive:
  enable: true # 是否启用脱敏,全局生效,默认开启
  depth: false # 是否启用深度脱敏,为了性能考虑,默认关闭,支持复杂对象,嵌套对象,对象内多层级嵌套,自动寻找返回值中嵌套对象包含的需脱敏的属性;
  #depth为true,且packages不为空,当方法返回值嵌套的属性包含在packages下,则自动进行脱敏。
  packages: com.mos.secure # 扫描包路径,多个以英文逗号分隔
1
2
3
4
5

# 4.3 添加注解

注意:

  • 方法注解表示该方法的返回值需要脱敏
  • 属性注解标识具体的脱敏规则

# 4.3.1 添加方法注解

@Desensitization
public Obj test(){
    // 业务逻辑,构建返回对象Obj
    return Obj;
}
1
2
3
4
5

# 4.3.2 添加属性注解

@DesensitizationProp(SensitiveTypeEnum.MOBILE_PHONE)
private String mobile;
1
2

# 5、 默认类型说明

  • CHINESE_NAME //中文名
  • ID_CARD // 身份证号
  • FIXED_PHONE // 电话
  • MOBILE_PHONE // 手机
  • ADDRESS //地址
  • EMAIL //邮箱
  • BANK_CARD //银行卡号
  • PASSWORD // 密码
  • CUSTOM //自定义 (配合 DesensitizationProp 中preLength和sufLength 进行个性化定义)

# 6、支持日志脱敏

# 6.1 开启脱敏注解

sensitive:
  log-info:
    enable: true
    categories:
      - keywords: name,chineseName
        pre-length: 1
        suf-length: 1
      - keywords: mail,email
        pre-length: 3
        suf-length: 3
      - keywords: mobile,phone
        pre-length: 3
        suf-length: 4
      - keywords: address,addr
        pre-length: 3
        suf-length: 4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 6.2 修改logback.xml

很简单,在logback.xml最前面添加一行(重写原%msg规则的实现)

注意:考虑到性能以及实用性的问题,复杂的嵌套对象暂未解析,即只解析对象的第一层属性。

 <conversionRule conversionWord="msg" converterClass="io.gitee.chemors.secure.ext.log.core.LogBackCoreConverter"/>
1

# 6.3 基于字符串的脱敏(语法有调整)

由于脱敏是基于key-value模式,因此需要指定key,才可以解析出脱敏规则,因此语法需稍微调整为:空格+key^{}+空格 ;

 log.info("基于字符串的脱敏---》name is name^{} , and mobile is mobile^{}",name, mobile);
1