ValidateApiAOP.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package com.fdkankan.openApi.component;
  2. import cn.hutool.core.util.StrUtil;
  3. import com.fdkankan.common.constant.ErrorCode;
  4. import com.fdkankan.common.exception.BusinessException;
  5. import com.fdkankan.openApi.util.TokenUtil;
  6. import org.apache.commons.lang3.StringUtils;
  7. import org.aspectj.lang.ProceedingJoinPoint;
  8. import org.aspectj.lang.annotation.Around;
  9. import org.aspectj.lang.annotation.Aspect;
  10. import org.aspectj.lang.annotation.Pointcut;
  11. import org.aspectj.lang.reflect.MethodSignature;
  12. import org.springframework.stereotype.Component;
  13. import org.springframework.web.context.request.RequestContextHolder;
  14. import org.springframework.web.context.request.ServletRequestAttributes;
  15. import javax.servlet.http.HttpServletRequest;
  16. import java.lang.reflect.Method;
  17. import java.util.Objects;
  18. @Component
  19. @Aspect
  20. public class ValidateApiAOP {
  21. @Pointcut("@annotation(com.fdkankan.openApi.component.ValidateApi)")
  22. public void pointCut(){}
  23. @Around("pointCut()")
  24. public Object handle(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
  25. //获取请求对象
  26. ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  27. HttpServletRequest request = servletRequestAttributes.getRequest();
  28. //处理
  29. //请求头
  30. String authorization = request.getHeader("Authorization");
  31. if(StrUtil.isEmpty(authorization)){
  32. throw new BusinessException(ErrorCode.AUTH_FAIL);
  33. }
  34. if (!TokenUtil.validateToken(authorization)){
  35. throw new BusinessException(ErrorCode.AUTH_FAIL);
  36. }
  37. //注解处理
  38. Class<?> clazz = proceedingJoinPoint.getTarget().getClass();
  39. //方法签名
  40. MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
  41. Method method = clazz.getDeclaredMethod(methodSignature.getName(), methodSignature.getParameterTypes());
  42. return proceedingJoinPoint.proceed();
  43. }
  44. }