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

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

SpringBoot使⽤AOP+注解实现简单的权限验证的⽅法
SpringAOP的介绍:
demo介绍
主要通过⾃定义注解,使⽤SpringAOP的环绕通知拦截请求,判断该⽅法是否有⾃定义注解,然后判断该⽤户是否有该权限。

这⾥做的⽐较简单,只有两个权限:⼀个普通⽤户、⼀个管理员。

项⽬搭建
这⾥是基于SpringBoot的,对于SpringBoot项⽬的搭建就不说了。

在项⽬中添加AOP的依赖:<!--more--->
<!--AOP包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
⾃定义注解及解析
在⽅法上添加该注解,说明该⽅法需要管理员权限才能访问。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Permission {
String authorities() default "ADMIN";
}
解析类:通过AOP的环绕通知获取⽅法上的注解,判断是否有Permission注解,返回注解的值。

public class AnnotationParse {
/***
* 解析权限注解
* @return 返回注解的authorities值
* @throws Exception
*/
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(){}
/**
* 权限环绕通知
* @param joinPoint
* @throws Throwable
*/
@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();
("访问⽤户,{}",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既可
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

相关文档
最新文档