SignVerifyAspect.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package com.fdkankan.ucenter.aop;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.fdkankan.redis.util.RedisUtil;
  4. import com.fdkankan.sign.SignUtils;
  5. import com.fdkankan.ucenter.annotation.VerifySign;
  6. import com.fdkankan.ucenter.common.constants.ResultCode;
  7. import com.fdkankan.ucenter.entity.AppSecret;
  8. import com.fdkankan.ucenter.exception.BusinessException;
  9. import com.fdkankan.ucenter.service.IAppSecretService;
  10. import lombok.extern.slf4j.Slf4j;
  11. import org.apache.commons.lang3.StringUtils;
  12. import org.aspectj.lang.ProceedingJoinPoint;
  13. import org.aspectj.lang.annotation.Around;
  14. import org.aspectj.lang.annotation.Aspect;
  15. import org.springframework.beans.factory.annotation.Autowired;
  16. import org.springframework.stereotype.Component;
  17. import org.springframework.web.context.request.RequestContextHolder;
  18. import org.springframework.web.context.request.ServletRequestAttributes;
  19. import javax.servlet.http.HttpServletRequest;
  20. import java.util.*;
  21. @Aspect
  22. @Component
  23. @Slf4j
  24. public class SignVerifyAspect {
  25. @Autowired
  26. IAppSecretService appSecretService;
  27. @Autowired
  28. RedisUtil redisUtil;
  29. @Around("@annotation(verifySign)")
  30. public Object verifySign(ProceedingJoinPoint joinPoint, VerifySign verifySign) throws Throwable {
  31. if (!verifySign.enabled()) {
  32. return joinPoint.proceed();
  33. }
  34. HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  35. String header = request.getHeader("X-UA");
  36. if(StringUtils.isNotBlank(header)){
  37. return joinPoint.proceed();
  38. }
  39. String sign = request.getHeader(verifySign.signParam().toLowerCase());
  40. String appId = request.getHeader(verifySign.appId().toLowerCase());
  41. log.info("verifySign--requestPath:{},sign:{},appId:{}",request.getRequestURL(),sign,appId);
  42. AppSecret byAppId = null;
  43. if(redisUtil.hasKey("ucenter:sign:appid:"+appId)){
  44. byAppId = JSONObject.parseObject(redisUtil.get("ucenter:sign:appid:"+appId),AppSecret.class);
  45. }else {
  46. byAppId = appSecretService.getByAppId(appId);
  47. }
  48. if(byAppId == null){
  49. throw new BusinessException(ResultCode.SIGN_ERROR);
  50. }
  51. if(!SignUtils.checkSign(sign,appId,byAppId.getPrivateKey())){
  52. throw new BusinessException(ResultCode.SIGN_ERROR);
  53. }
  54. if(!redisUtil.hasKey("ucenter:sign:appid:"+appId)){
  55. redisUtil.set("ucenter:sign:appid:"+appId, JSONObject.toJSONString(byAppId),60 *60 *2);
  56. }
  57. return joinPoint.proceed();
  58. }
  59. }