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

相关推荐
Aision_4 小时前
从工具调用到 MCP、Skill完整学习记录
java·python·gpt·学习·langchain·prompt·agi
zc.z8 小时前
JAVA实现:纯PCM格式音频转换成BASE64
java·音视频·pcm
mask哥8 小时前
力扣算法java实现汇总整理(上)
java·算法·leetcode
无风听海8 小时前
深入剖析 YARP 的 Transforms:构建灵活的反向代理转换管道
后端·中间件·asp.net
Gopher_HBo8 小时前
负载均衡
后端
自由生长20249 小时前
RAG已死?什么标题党啊!
后端
Aaswk9 小时前
Java Lambda 表达式与流处理
java·开发语言·python
是宇写的啊9 小时前
Spring AOP
java·spring
万邦科技Lafite10 小时前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
东方小月10 小时前
5分钟搞懂Harness Engineering(驾驭工程):从提示词到AI Agent的进化之路
前端·后端·架构