SpringBoot使用AOP+注解實現(xiàn)簡單的權限驗證的方法
SpringAOP的介紹:傳送門
demo介紹
主要通過自定義注解,使用SpringAOP的環(huán)繞通知攔截請求,判斷該方法是否有自定義注解,然后判斷該用戶是否有該權限。這里做的比較簡單,只有兩個權限:一個普通用戶、一個管理員。
項目搭建
這里是基于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的環(huán)繞通知獲取方法上的注解,判斷是否有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環(huán)繞通知
@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(){}
/**
* 權限環(huán)繞通知
* @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 {
//獲取當前用戶的權限,這里是自定義的發(fā)那個發(fā)
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既可
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- SpringBoot中使用AOP打印接口日志的方法
- SpringBoot中創(chuàng)建的AOP不生效的原因及解決
- springboot?aop里的@Pointcut()的配置方式
- SpringBoot AOP方式實現(xiàn)多數(shù)據(jù)源切換的方法
- SpringBoot項目中使用AOP的方法
- 詳解基于SpringBoot使用AOP技術實現(xiàn)操作日志管理
- springboot配置aop切面日志打印過程解析
- SpringBoot使用AOP實現(xiàn)統(tǒng)計全局接口訪問次數(shù)詳解
- SpringBoot中使用AOP實現(xiàn)日志記錄功能
- SpringBoot中AOP的多種用途與實踐指南
相關文章
JAVA后臺轉換成樹結構數(shù)據(jù)返回給前端的實現(xiàn)方法
這篇文章主要介紹了JAVA后臺轉換成樹結構數(shù)據(jù)返回給前端的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03
Spring MVC溫故而知新系列教程之請求映射RequestMapping注解
這篇文章主要介紹了Spring MVC溫故而知新系列教程之請求映射RequestMapping注解的相關知識,文中給大家介紹了RequestMapping注解提供的幾個屬性及注解說明,感興趣的朋友跟隨腳本之家小編一起學習吧2018-05-05
解決springboot項目找不到resources目錄下的資源問題
這篇文章主要介紹了解決springboot項目找不到resources目錄下的資源問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08

