使用SpringAOP优化请求响应解密加密流程

2020-09-14  本文已影响0人  猴子的烟枪

在Spring基础上使用自定义AOP,主要有以下两种

Spring还有几种可以让开发者自己扩展的AOP,相比上面介绍的AOP,主要体现在切入点是固定的,开发者需要自己实现相应的Advice。

现在我们的业务需求是这样的:

APP使用对称加秘钥将参数json串加密,加密报文通过BasePayParam对象传输给后台,后台将BasePayParam对象的密文解密为json,再转化为对象处理业务。之前的处理逻辑是这样的:

public class BasePayParam {
    /**传输的密文*/
    private String param;
}
@PostMapping(value = "/pay")
public BasePayVo bindPhone(@RequestBody BasePayParam basePayParam ) {
   //具体的解密逻辑就在一下的serVice完成
    return bindPhoneService.bindPhone(basePayParam);
}

-Service层解密参数并转化为相应的对象

public BasePayVo bindPhone( BasePayParam basePayParam) {
        // 解密参数
        String dgutPayAesKey =  "AB222222222";
        String param = basePayParam.getParam();
               //把加密报文转化为对象
        BindPhoneReq bindPhoneDto= checkParamsService.deAESParam(param, dgutPayAesKey, BindPhoneReq.class);
               ......
               //把参数加密返回APP
        String enAESRsp = checkParamsService.enAESParam(JsonUtil.Object2Json(result).trim(), dgutPayAesKey);
        basePayVo .setData(enAESRsp);
               return basePayVo ;
}

加解密的处理代码在service层的每个方法都使用一遍。这种做法是非常浪费效率的,显得啰里啰嗦,没有方法的复用确实让人受不了。作为一个很懒的程序员,我要用AOP优化一下。因为我们的业务处理逻辑是高度一致的:解密报文->处理业务->加密返回数据。自然而然应该有这个思路:使用AOP简化处理。

优化后处理流程

1.自定义注解

/**
 * 解密注解
 * @Author zhouyu
 * @date 2020/9/8 9:54
 **/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Decrypt {
    String value() default "";
}

/**
 * 加密注解
 * @Author zhouyu
 * @date 2020/9/8 9:55
 **/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Encrypt {
    String value() default "";
}

2.入参解密处理

@RestControllerAdvice(basePackageClasses = {com.dgut.web.pay.icbc.IcbcPayQrController.class,
        com.dgut.web.pay.unipay.UnipayQrController.class})
public class DecryRequestBodyAdvice implements RequestBodyAdvice {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SystemConfigRepository systemConfigRepository;

    public String getPayAesKey() {
        return "112121212121212";
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        //只解析带有@RequestBody注解
        return methodParameter.hasParameterAnnotation(RequestBody.class);
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        if (methodParameter.getMethod().isAnnotationPresent(Decrypt.class)) {
            return new HttpInputMessage() {
                @Override
                public InputStream getBody() {
                    try {
                        String bodyStr = IOUtils.toString(httpInputMessage.getBody(), "utf-8");
                        JsonObject jsonObject = new JsonParser().parse(bodyStr).getAsJsonObject();
                        JsonElement jsonElement = jsonObject.get("param");
                        if (jsonElement != null) {
                            //解密
                            String encrtStr = jsonElement.getAsString();
                            bodyStr = AesAlgorithmUtil.DecryptAES(encrtStr,getPayAesKey());
                        }
                        return IOUtils.toInputStream(bodyStr, "utf-8");
                    } catch (Exception e) {
                        logger.error("解密参数异常", e);
                        throw new RuntimeException("参数解密异常");
                    }
                }

                @Override
                public HttpHeaders getHeaders() {
                    return httpInputMessage.getHeaders();
                }
            };
        } else {
            return httpInputMessage;
        }
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }
}

controller直接使用@RequestBody 接收解密后的参数,并加上刚才自定义的注解。

@Encrypt
@Decrypt
@PostMapping(value = "/pay")
public BasePayVo bindPhone(@RequestBody BindPhoneReq bindPhoneDto) {
   //下面的service就不需要解密、加密啦
    return bindPhoneService.bindPhone(bindPhoneDto);
}

3.响应加密处理

@RestControllerAdvice(basePackageClasses = {com.dgut.web.pay.icbc.IcbcPayQrController.class,
        com.dgut.web.pay.unipay.UnipayQrController.class})
public class EncryResponseBodyAdvice implements ResponseBodyAdvice {
    private Logger logger = LoggerFactory.getLogger(EncryResponseBodyAdvice.class);
    @Autowired
    private SystemConfigRepository systemConfigRepository;

    public String getPayAesKey() {
        return "112121212121212";
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object bodyObj, MethodParameter methodParameter, MediaType mediaType, Class aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (methodParameter.getMethod().isAnnotationPresent(Encrypt.class)) {
            if (bodyObj instanceof BasePayVo) {
                BasePayVo resBody = (BasePayVo) bodyObj;
                Object encryData = resBody.getInfo();
                if (encryData != null) {
                    try {
                        //将body加密后返回
                        String jsonData = JsonUtil.Object2Json(encryData);
                        String aesEncryptData = AesAlgorithmUtil.EncryptAES(jsonData, getPayAesKey());
                        resBody.setInfo(aesEncryptData);
                    } catch (Exception e) {
                        logger.error("加密参数异常", e);
                    }
                } else {
                    return bodyObj;
                }
            }
        }
        return bodyObj;
    }
}

到此为止,所有的service层的重复使用的加密解密代码就可以逐步去掉了。

上一篇下一篇

猜你喜欢

热点阅读