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的用户发送到这个路径的请求才能被放行处理。这样就特别灵活。

相关推荐
Warson_L1 小时前
python - set/tuple/dict quiz
后端
IT_Octopus2 小时前
Spring Boot 实战:@PostConstruct + Caffeine 缓存初始化与定时刷新
spring boot·后端·缓存
swipe2 小时前
从本地开发到生产部署:用 Docker Compose 跑通 NestJS、MySQL 与 Milvus
后端·langchain·llm
码事漫谈2 小时前
SenseNova Skills Studio:为商汤SenseNova U1打造的本地办公技能包
后端
zhangxingchao2 小时前
AI应用开发七:可以替代 RAG 的技术
前端·人工智能·后端
Java面试题总结3 小时前
java高频面试题(2026最新)
java·开发语言·jvm·数据库·spring·缓存
苦逼的猿宝3 小时前
学生心理咨询评估系统
java·毕业设计·springboot·计算机毕业设计
隔窗听雨眠3 小时前
doctype、charset、meta如何控制整个渲染流水线
java·服务器·前端
excel3 小时前
🧠 Prisma 表名大写 vs SQL 导出小写问题深度解析(附踩坑与解决方案)
前端·后端
GetcharZp4 小时前
Hermes Agent:一个真正“会成长”的开源 AI Agent,正在改变 AI 自动化玩法
后端