栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot使用AOP+注解实现简单的权限验证的方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot使用AOP+注解实现简单的权限验证的方法

SpringAOP的介绍:传送门

demo介绍

主要通过自定义注解,使用SpringAOP的环绕通知拦截请求,判断该方法是否有自定义注解,然后判断该用户是否有该权限。这里做的比较简单,只有两个权限:一个普通用户、一个管理员。

项目搭建

这里是基于SpringBoot的,对于SpringBoot项目的搭建就不说了。在项目中添加AOP的依赖:



  org.springframework.boot
  spring-boot-starter-aop

自定义注解及解析

在方法上添加该注解,说明该方法需要管理员权限才能访问。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@documented
public @interface Permission {

   String authorities() default "ADMIN";

}

解析类:通过AOP的环绕通知获取方法上的注解,判断是否有Permission注解,返回注解的值。

public class AnnotationParse {
  
  public static String privilegeParse(Method method) throws Exception {
    //获取该方法
    if(method.isAnnotationPresent(Permission.class)){
      Permission annotation = method.getAnnotation(Permission.class);
      return annotation.authorities();
    }
    return null;
  }
}

SpringAOP环绕通知

@Aspect
@Component
public class ControllerAspect {

  private final static Logger logger = LoggerFactory.getLogger(ControllerAspect.class);

  @Autowired
  private UserService userService;
  
  @Pointcut("execution(public * com.wqh.blog.controller.*.*(..))")
  public void privilege(){}

  
  @ResponseBody
  @Around("privilege()")
  public Object isAccessMethod(ProceedingJoinPoint joinPoint) throws Throwable {
    //获取访问目标方法
    MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
    Method targetMethod = methodSignature.getMethod();
    //得到方法的访问权限
    final String methodAccess = AnnotationParse.privilegeParse(targetMethod);

    //如果该方法上没有权限注解,直接调用目标方法
    if(StringUtils.isBlank(methodAccess)){
      return joinPoint.proceed();
    }else {
      //获取当前用户的权限,这里是自定义的发那个发
      User currentUser = userService.getCurrentUser();
      logger.info("访问用户,{}",currentUser.toString());
      if(currentUser == null){
 throw new LoginException(ResultEnum.LOGIN_ERROR);
      }
      if(methodAccess.equals(currentUser.getRole().toString())){
 return joinPoint.proceed();
      }else {
 throw new BusinessException(ResultEnum.ROLE_ERROR);
      }
    }
  }
}

使用

只需要在需要验证的方法上添加自定义注解: @Permission既可

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/138106.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号