乐趣区

关于后端:自定义注解使用AOP做权限校验

你好,我是程序员 Alan, 很快乐遇见你。

最近看 RocketMQ 源码时,发现它是应用自定义注解的形式做权限校验,蛮有意思的,于是简略上手试了一下。

上面是局部代码。

自定义注解

import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Permission {String permission() default "";
}

编写切面

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import org.aspectj.lang.reflect.MethodSignature;
@Component
@Aspect
public class PermissionAnnotationAspect {@Pointcut("@annotation(com.esandinfo.pclogin.permission.Permission)")
    private void permission() {}
    @Around("permission()")
    public void advice(ProceedingJoinPoint joinPoint) throws Throwable {MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        if (!method.isAnnotationPresent(Permission.class)) {joinPoint.proceed(); // 没有应用注解默认放行
        } else {Permission permission = fetchPermission(methodSignature);
            //[1] 取出申请方的权限信息
            String userPermission = "TEST"; // 假如用户权限为 TEST
            System.out.println("用户权限:" + userPermission);
            //[2] 和注解的值做比拟 permission.permission()
            if (userPermission.equals(permission.permission())){//[3] 校验通过放行用户
                System.out.println("放行");
                joinPoint.proceed();}
           return;
        }
    }
    private Permission fetchPermission(MethodSignature methodSignature) {return methodSignature.getMethod().getAnnotation(Permission.class);
    }
}

测试

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PermissionAnnotationController {@RequestMapping(value = "/public/testMethod")
    @Permission(permission = "TEST")
    public void testMethod(){}
}

测试后果

退出移动版