自定义注解实现权限校验

自定义注解实现权限校验

引入所需的依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>版本号</version>
    <relativePath/>
</parent>
<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
     <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-aop</artifactId>
     </dependency>
</dependencies>

自定义注解(RequiresPermission)

import java.lang.annotation.ElementType;  
import java.lang.annotation.Retention;  
import java.lang.annotation.RetentionPolicy;  
import java.lang.annotation.Target;  

@Target({ElementType.METHOD,ElementType.TYPE})// 标识这个注解可以用在方法上
@Retention(RetentionPolicy.RUNTIME)  // 在运行时仍然可以获取到注解
public @interface RequiresPermission {  
    String value();  // 权限标识  
}  

定义AOP切面类

在切面中,我们将使用ProceedingJoinPoint对象来拦截带有@RequiresPermission注解的方法并获取其中的值:

@Aspect  
@Component  
public class PermissionAspect {  
    //需要使用全路径名指定自定义注解
    @Around("@annotation(com.chs.annocation.RequiresPermission)")
    public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable {  
        // 获取被调用的方法  
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();  
        
        // 获取RequiresPermission注解  
        RequiresPermission requiresPermission = method.getAnnotation(RequiresPermission.class);  

        // 获取权限值  
        String permission = requiresPermission.value();  
        
        // 在这里执行权限检查  
        if (!checkUserPermission(permission)) {  
            throw new SecurityException("权限不足");  
        }  

        return joinPoint.proceed();  // 继续执行被拦截的方法  
    }  

    private boolean checkUserPermission(String permission) {  
        // 权限检查逻辑,返回true或false  
    }  
}  

使用自定义注解的控制器

@RestController  
public class UserController {  

    @GetMapping("/admin")  
    @RequiresPermission("ADMIN")  // 需要ADMIN权限  
    public String adminEndpoint() {  
        return "Welcome to admin area";  
    }  

    @GetMapping("/user")  
    @RequiresPermission("USER")  // 需要USER权限  
    public String userEndpoint() {  
        return "Welcome to user area";  
    }  
}  

注意:记得在主启动类上加:@EnableAspectJAutoProxy

posted @   CH_song  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示