前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >自定义注解使用AOP做权限校验

自定义注解使用AOP做权限校验

原创
作者头像
程序员Alan
发布2022-11-03 16:53:19
2430
发布2022-11-03 16:53:19
举报
文章被收录于专栏:程序员Alan

你好,我是程序员Alan, 很高兴遇见你。

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

下面是部分代码。

自定义注解

代码语言:javascript
复制
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Permission {
    String permission() default "";
}

编写切面

代码语言:javascript
复制
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);
    }
}

测试

代码语言:javascript
复制
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(){
    }
}

测试结果

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 自定义注解
  • 编写切面
  • 测试
  • 测试结果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档