- 自定义一个注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface PreschoolAuth {
String value() default "#provinceCode";
}
- 定义增强
@Component
@Aspect
public class AuthAspect {
@Pointcut("@annotation(PreschoolAuth)")
public void authentication(){}
@Before("authentication()")
public void judge(JoinPoint joinPoint) {
// 获取被增强的方法注解的参数
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
PreschoolAuth auth = method.getAnnotation(PreschoolAuth.class);
String key = auth.value();
// 根据注解的参数获得被增强的方法的参数
Object[] args = joinPoint.getArgs();
List<String> codes = ParamUtil.parseExpression(key, method, args, List.class);
if (CollectionUtils.isEmpty(codes)){
throw new BizException(ErrorCode.PERMISSION_DENIED);
}
// 获取区划码
String code = codes.get(0);
// 获取请求头
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes)requestAttributes;
HttpServletRequest request = sra.getRequest();
String secret = request.getHeader("XXXX");
if(StringUtils.isBlank(secret)) {
throw new BizException(ErrorCode.XXXXXX);
}
// 做校验 do.......
}
}
- 在需要增强的方法上使用注解
@PreschoolAuth(value = "#provinceCode")
public Object query(String provinceCode,.... ) {
return ....;
}
public class ParamUtil {
public static <T> T parseExpression(String expression, Method method, Object[] args, Class<T> classType) {
if (StringUtils.isBlank(expression)) {
return null;
} else if (!expression.trim().startsWith("#") && !expression.trim().startsWith("$")) {
return null;
} else {
LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
String[] paramNames = discoverer.getParameterNames(method);
if (ArrayUtils.isEmpty(paramNames)) {
return null;
} else {
StandardEvaluationContext context = new StandardEvaluationContext();
for (int i = 0; i < paramNames.length; ++i) {
context.setVariable(paramNames[i], args[i]);
}
return (new SpelExpressionParser()).parseExpression(expression).getValue(context, classType);
}
}
}
}
网友评论