springboot使用切面编程,实现不同角色账号看到的数据不同

本文介绍了如何在SpringBoot应用中使用切面编程实现基于角色的访问控制,通过自定义注解和切面类,确保不同角色的用户只能访问相应权限的数据。
摘要由CSDN通过智能技术生成

在Spring Boot中,可以使用切面编程来实现不同角色账号看到的数据不同的功能。下面是一个示例:

首先,定义一个自定义的注解 @RoleAccess,用于标注在需要进行角色访问控制的方法上:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RoleAccess {
    String[] roles();
}

接着,创建一个切面类 RoleAccessAspect,用于拦截带有 @RoleAccess 注解的方法,并根据当前用户的角色进行访问控制:

@Aspect
@Component
public class RoleAccessAspect {
    
    @Before("@annotation(roleAccess)")
    public void before(JoinPoint joinPoint, RoleAccess roleAccess) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            String currentRole = authentication.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .collect(Collectors.joining(","));
            if (!Arrays.asList(roleAccess.roles()).contains(currentRole)) {
                throw new AccessDeniedException("Access Denied");
            }
        }
    }
}

在上面的切面类中,通过 @Before 注解和 @annotation(roleAccess) 使用了切点表达式,表示拦截带有 @RoleAccess 注解的方法,并在方法执行前进行访问控制。

然后,在需要进行访问控制的方法上添加 @RoleAccess 注解,指定不同角色具有访问权限的配置,例如:

@RestController
public class DataController {
    
    @RoleAccess(roles = {"admin"})
    @GetMapping("/data")
    public String getDataForAdmin() {
        return "This data is only accessible to admins";
    }
    
    @RoleAccess(roles = {"user"})
    @GetMapping("/data")
    public String getDataForUser() {
        return "This data is only accessible to users";
    }
}

在上面的示例中,同一个接口路径 /data 根据不同角色的配置,返回不同的数据。

最后,需要在启动类上添加 @EnableAspectJAutoProxy 注解启用切面:

@SpringBootApplication
@EnableAspectJAutoProxy
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

这样,当不同角色的账号访问相应的接口时,切面会根据当前用户的角色进行访问控制,确保只有具有访问权限的角色可以看到相应的数据。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了一种称为切面编程(Aspect-Oriented Programming,AOP)的方式来实现横向关注点的分离模块化。AOP允许开发者通过定义切面来将与业务逻辑无直接关联的横切关注点(如日志记录、事务管理等)从主要业务逻辑中分离出来。 在Spring Boot中,使用AOP的关键是定义切面和连接点。切面(Aspect)是一个包含了通知(Advice)和切点(Pointcut)的类。通知定义了在连接点执行之前、之后或周围执行的代码逻辑,而切点则定义了哪些连接点应该被应用通知。 要使用AOP,首先需要在Spring Boot应用中添加`spring-boot-starter-aop`依赖。然后,可以通过创建一个带有`@Aspect`注解的类来定义切面。在该类中,可以使用`@Before`、`@After`、`@Around`等注解来定义不同类型的通知,并通过`@Pointcut`注解来定义切点表达式。 以下是一个简单的示例: ```java import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; @Aspect @Component public class LoggingAspect { @Before("execution(public * com.example.demo.MyService.*(..))") public void beforeMethod() { System.out.println("Before method execution"); } @After("execution(public * com.example.demo.MyService.*(..))") public void afterMethod() { System.out.println("After method execution"); } @Around("execution(public * com.example.demo.MyService.*(..))") public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("Before method execution"); Object result = joinPoint.proceed(); System.out.println("After method execution"); return result; } } ``` 在上述示例中,`@Before`、`@After`和`@Around`注解分别定义了三种通知类型的方法,并使用`@Pointcut`注解定义了切点表达式。这里的切点表达式表示对`com.example.demo.MyService`类中所有公共方法的调用进行通知。 通过使用AOP,可以在不修改原始业务逻辑的情况下,将横切关注点应用到应用程序中的特定连接点上,从而实现更好的代码复用和可维护性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值