SpringBoot AOP 简单的权限校验

本篇文章的主要内容是通过AOP切面编程实现简单的权限校验。

书接上回登录与注册功能

我们的用户表里面不是有role(权限)这个字段吗

在JWT令牌的生成中,我们加入了role字段。

那么接下来,我们就可以通过这个字段来实现权限校验。

我这里就很简单,只有一个Permission注解和一个PermissionAspect类

Permission

java 复制代码
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface Permission {
    /**
     * 最小权限
     * @return
     */
    int role() default 0;
}

PermissionAspect类:

java 复制代码
@Slf4j
@Aspect
@Component
public class PermissionAspect {
    // 定义切点
    @Pointcut("within(@org.springframework.web.bind.annotation.RestController *) && @annotation(com.codehome.server.annotation.Permission)")
    public void autoPermissionPointcut(){

    }

    // 定义通知
    @Before("autoPermissionPointcut()")
    public void requirePermission(final JoinPoint joinPoint)throws PermissionException {
        log.info("权限校验开始");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Permission permission = signature.getMethod().getAnnotation(Permission.class);
        Integer role = permission.role();
        if(BaseContext.getCurrentRole() >= role){
            log.info("权限校验通过");
        }else {
            throw new PermissionException("权限不足");
        }

    }
}

说明:在JWT令牌生成的时候我们存入了role,在JwtTokenAdminInterceptor拦截器中,我们将这个role取了出来并保存到了ThreadLocal中,所以在校验的时候,就通过这个role进行权限校验。

权限校验使用:

在Controller类中,我们在每个路径方法前加上我们写的注解@Permission(role=2),这个就代表着只有用户权限大于等于2的用户发送到这个路径的请求才能被放行处理。这样就特别灵活。

相关推荐
SunnyDays101118 分钟前
如何使用 Java 自动调整 Excel 行高和列宽
java·自动调整行高和列宽·自适应行高和列宽
虎头金猫23 分钟前
内网导航站 “出圈”!用 cpolar 解锁 Dashy 远程访问新玩法
java·c++·python·程序人生·职场和发展·php·程序员创富
csdn_aspnet26 分钟前
如何在 ASP.NET Core Identity 中实现用户身份验证
后端·asp.net·.net core·identity
康小庄27 分钟前
SpringBoot 拦截器 (Interceptor) 与切面 (AOP):示例、作用、及适用场景
java·数据库·spring boot·后端·mysql·spring·spring cloud
不会c+30 分钟前
Maven私服的搭建与使用
java·maven
weixin_4365250739 分钟前
若依多租户版: RuoYi-Vue-Plus
java
野生技术架构师40 分钟前
深度拆解JVM垃圾回收:可达性分析原理+全类型回收器执行机制
java·开发语言·jvm
中科院提名者43 分钟前
如何配置go环境并用vscode运行
开发语言·后端·golang
qq_12498707531 小时前
基于springboot+vue的家乡特色旅游宣传推荐系统(源码+论文+部署+安装)
java·前端·vue.js·spring boot·毕业设计·计算机毕设·计算机毕业设计
菜菜小狗的学习笔记1 小时前
黑马程序员java web学习笔记--后端进阶(一)AOP
java·笔记·学习