api接口针对id字段的加密-数字ID变字符串
效果图:
语言:JAVA
框架:SpringBoot
说明:
无需其它配置,按下面参考类即可实现接口返回ID变为随机密文,对业务无侵入
建议:
加密的KEY最好是用户登录成功之后再生成一个随机的KEY,安全性更高
实现代码:
/** 注解 **/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerialize(using = IdHashSerializer.class)
@JsonDeserialize(using = IdHashDeserializer.class)
public @interface IdHash {
}/** 加密类 **/
@Slf4j
public class IdHashSerializer extends JsonSerializer {
private HttpServletRequest request;
public IdHashSerializer(HttpServletRequest request) {
// Spring会自动注入
this.request = request;
}
@Override
public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if(value == null) return;
Object secretKey = request.getAttribute("D-Secret-Key"); //// 全局KEY 或 用户登录成功生成随机KEY
if(secretKey == null) {
gen.writeNumber(value);
return;
}
try {
////// 加密算法参考
gen.writeString(AesUtils.urlEncrypt(value.toString(), secretKey.toString()));
} catch (Exception e) {
log.warn("[idhash] serialize fail. value: {}, uid: {}", value, request.getAttribute("D-User-Id"));
throw new KnownException("90001", "无效的请求");
}
}
} /** 解密类 **/
@Slf4j
public class IdHashDeserializer extends JsonDeserializer {
private HttpServletRequest request;
public IdHashDeserializer(HttpServletRequest request) {
this.request = request;
}
@Override
public Long deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String value = p.getText();
if(StringUtils.isEmpty(value)) {
return null;
}
Object secretKey = request.getAttribute("D-Secret-Key"); //// 全局KEY 或 用户登录成功生成随机KEY
if(secretKey != null) {
try {
return Long.parseLong(AesUtils.urlDecrypt(value, secretKey.toString()));
} catch (Exception e) {
log.warn("[idhash] deserialize fail. value: {}, uid: {}", value, request.getAttribute("D-User-Id"));
throw new KnownException("90002", "无效的请求,请刷新页面后重试");
}
}
return Long.parseLong(value);
}
} 使用示例:
@Getter
@Setter
@Schema(description = "保存-菜单")
public class SaveMenuDto {
@IdHash/** 注解 **/
@Schema(description = "菜单ID")
private Long id;
@IdHash/** 注解 **/
@Schema(description = "上级菜单ID")
@JsonSetter(nulls = Nulls.SKIP)
private Long pid = 0L;
...
}@Getter
@Setter
public class QueryTreeVo implements BaseVo {
@IdHash/** 注解 **/
private Long id;
private String title;
private Integer status;
private Boolean leaf = true;
}
上一篇:太离谱了,我实在是憋不住了
下一篇:关于小程序代码被破解如何解救?
相关文章
- Linux服务器硬件信息查询与日常运维命令总结
- Linux服务器带宽跑不满?用ethtool调优网卡参数,性能提升30%
- 如何在 Rocky Linux 中查看网卡流量?跟着小编学习iftop安装和使用
- Linux查看网卡速率_linux查看网卡当前速率
- 五一我要看七天小说!免费开源的轻量化书库talebook搭建流程。
- 我是如何用这3个小工具,助力小姐姐提升100%开发效率的
- html5和css3的常用参考网_基于html5和css3的网页制作
- 超详细的网络抓包神器 tcpdump 使用指南
- Vue 技术栈(全家桶)_vue全栈项目教程
- 学习ES6- 入门Vue(大量源代码及笔记,带你起飞)
