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

相关推荐
y = xⁿ4 分钟前
【从零开始学习Redis|第四篇】从底层理解缓存问题:雪崩、击穿、穿透与一致性设计
java·redis·学习·缓存
江湖有缘7 分钟前
本地化JSON 处理新方案:基于 Docker的JSON Hero部署全记录
java·docker·json
XPoet10 分钟前
AI 编程工程化:Rule——给你的 AI 员工立规矩
前端·后端·ai编程
御坂10101号21 分钟前
「2>&1」是什么意思?半个世纪的 Unix 谜题
java·数据库·bash·unix
韩立学长28 分钟前
基于Springboot校园志愿者服务平台77pz7812(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
Java基基44 分钟前
Spring让Java慢了30倍,JIT、AOT等让Java比Python快13倍,比C慢17%
java·开发语言·后端·spring
future02101 小时前
Spring AOP核心机制:代理与拦截揭秘
java·开发语言·spring·面试·aop
qq_12498707531 小时前
基于SpringBoot微信小程序的智能在线预约挂号系统(源码+论文+部署+安装)
spring boot·后端·微信小程序·毕业设计·计算机毕设·毕业设计源码
代码探秘者1 小时前
【Redis】分布式锁深度解析:实现、可重入、主从一致性与强一致方案
java·数据库·redis·分布式·缓存·面试
小马爱打代码1 小时前
SpringBoot + 异地多活 + 消息回放:金融级数据一致性容灾架构设计与演练
spring boot·金融