SpringBoot使用AOP+注解实现简单的权限验证的方法
SpringAOP的介绍:传送门
demo介绍
主要通过自定义注解,使用SpringAOP的环绕通知拦截请求,判断该方法是否有自定义注解,然后判断该用户是否有该权限。这里做的比较简单,只有两个权限:一个普通用户、一个管理员。
项目搭建
这里是基于SpringBoot的,对于SpringBoot项目的搭建就不说了。在项目中添加AOP的依赖:
org.springframework.boot spring-boot-starter-aop
自定义注解及解析
在方法上添加该注解,说明该方法需要管理员权限才能访问。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public@interfacePermission{
Stringauthorities()default"ADMIN";
}
解析类:通过AOP的环绕通知获取方法上的注解,判断是否有Permission注解,返回注解的值。
publicclassAnnotationParse{
/***
*解析权限注解
*@return返回注解的authorities值
*@throwsException
*/
publicstaticStringprivilegeParse(Methodmethod)throwsException{
//获取该方法
if(method.isAnnotationPresent(Permission.class)){
Permissionannotation=method.getAnnotation(Permission.class);
returnannotation.authorities();
}
returnnull;
}
}
SpringAOP环绕通知
@Aspect
@Component
publicclassControllerAspect{
privatefinalstaticLoggerlogger=LoggerFactory.getLogger(ControllerAspect.class);
@Autowired
privateUserServiceuserService;
/**
*定义切点
*/
@Pointcut("execution(public*com.wqh.blog.controller.*.*(..))")
publicvoidprivilege(){}
/**
*权限环绕通知
*@paramjoinPoint
*@throwsThrowable
*/
@ResponseBody
@Around("privilege()")
publicObjectisAccessMethod(ProceedingJoinPointjoinPoint)throwsThrowable{
//获取访问目标方法
MethodSignaturemethodSignature=(MethodSignature)joinPoint.getSignature();
MethodtargetMethod=methodSignature.getMethod();
//得到方法的访问权限
finalStringmethodAccess=AnnotationParse.privilegeParse(targetMethod);
//如果该方法上没有权限注解,直接调用目标方法
if(StringUtils.isBlank(methodAccess)){
returnjoinPoint.proceed();
}else{
//获取当前用户的权限,这里是自定义的发那个发
UsercurrentUser=userService.getCurrentUser();
logger.info("访问用户,{}",currentUser.toString());
if(currentUser==null){
thrownewLoginException(ResultEnum.LOGIN_ERROR);
}
if(methodAccess.equals(currentUser.getRole().toString())){
returnjoinPoint.proceed();
}else{
thrownewBusinessException(ResultEnum.ROLE_ERROR);
}
}
}
}
使用
只需要在需要验证的方法上添加自定义注解:@Permission既可
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。