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

相关推荐
止语Lab6 小时前
Go并发编程实战:Channel 还是 Mutex?一个场景驱动的选择框架
开发语言·后端·golang
小码哥_常7 小时前
Spring Boot一键限速:守护你的接口“高速路”
后端
HoneyMoose7 小时前
Jenkins Cloudflare 部署提示错误
java·servlet·jenkins
阿丰资源7 小时前
基于SpringBoot的物流信息管理系统设计与实现(附资料)
java·spring boot·后端
Predestination王瀞潞7 小时前
Java EE3-我独自整合(第四章:Spring bean标签的常见配置)
java·spring·java-ee
overmind7 小时前
oeasy Python 121[专业选修]列表_多维列表运算_列表相加_列表相乘
java·windows·python
资深数据库专家7 小时前
总账EBS 应用服务器1 的监控分析
java·网络·数据库
房开民7 小时前
可变参数模板
java·开发语言·算法
t***5447 小时前
如何在现代C++中更有效地应用这些模式
java·开发语言·c++
_深海凉_7 小时前
LeetCode热题100-最小栈
java·数据结构·leetcode