场景
未经加密的传输可能导致数据在传输过程中被第三方截获,造成数据泄露。接口加密是应对数据安全威胁的关键应对措施,但是核心技术都是通过springboot提供的AOP技术
实践方案一:实现ResponseBodyAdvice
自定义注解
在需要加密的接口上通过实现自定义注解,对方法的返回值加密。定义加密注解:
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Encryption {
}
切面实现
@ControllerAdvice
@Slf4j
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice {
/**
* 判断当前方法的返回值是否需要进行加密处理。
*
* @param returnType 方法返回类型
* @param converterType 转换器类型
* @return 如果方法返回类型上标注了Encryption注解,则返回true,表示需要加密;否则返回false。
*/
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return returnType.hasMethodAnnotation(Encryption.class);
}
/**
* 在响应体写入之前对响应体进行加密处理。
*
* @param body 响应体内容
* @param returnType 方法返回类型
* @param selectedContentType 选中的内容类型
* @param selectedConverterType 选中的转换器类型
* @param request 请求对象
* @param response 响应对象
* @return 返回加密后的响应体内容。
*/
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if (Objects.isNull(body)){
return null;
}
log.info("加密前:{}", body);
// 这里使用的是Base64Encode加密,也可以使用其他加密方法
String s = EncryptUtil.Base64Encode(body.toString());
log.info("加密后:{}", s);
log.info("解密后:{}", EncryptUtil.Base64Decode(s));
return s;
}
}
方案二:责任链模式处理
其实在实际项目中不仅仅对接口进行加密处理还需要日志打印,包括一些其他的业务处理,这么一系列的操作都需要通过AOP进行业务前置操作,就可以通过责任链模式进行处理
设计模式-责任链模式