import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* 统一验签:
* 请求 json 添加 appSecret 字段,md5 加密后,丢到 sign 里,appSecret 不传,sign 必传
*
* @author jason
*/
@Slf4j
@Aspect
@Component
@Order(2)
public class SignAspect {
@Value("${api.appSecret:}")
private String appSecret;
@Pointcut("execution(public * com.xxx.xxx.controller.ApiQueryController.*(..))")
public void sign() {
}
/**
* 请求
*/
@Before("sign()")
public void doBefore(JoinPoint joinPoint) {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
assert attributes != null;
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
log.info("全局日志-请求URL: {}", request.getRequestURL().toString());
log.info("全局日志-请求URL参数: {}", request.getQueryString());
log.info("全局日志-请求方式: {}", request.getMethod());
log.info("全局日志-请求数据类型: {}", request.getContentType());
log.info("全局日志-请求数据编码: {}", request.getCharacterEncoding());
log.info("全局日志-请求IP: {}", request.getRemoteAddr());
log.info("全局日志-请求包名.方法名: {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
log.info("全局日志-请求参数: {}", JSONUtil.parseObj(joinPoint.getArgs()[0]));
JSONObject jsonObject = JSONUtil.parseObj(joinPoint.getArgs()[0]);
// 对方签名
String sign = jsonObject.getStr("sign");
jsonObject.set("appSecret", appSecret);
jsonObject.remove("sign");
// 我方签名
log.info("生成签名原始报文:{}", jsonObject.toString());
String mySign = SecureUtil.md5(jsonObject.toString());
log.info("验签,对方签名:{},我方签名:{}", sign, mySign);
// 验签
Assert.isTrue(StrUtil.equals(sign, mySign), "验签失败");
}
}
版权声明:本文为z1353095373原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。