SpringBoot使用AOP+註解實現簡單的權限驗證

SpringAOP的介紹:傳送門java

demo介紹

主要經過自定義註解,使用SpringAOP的環繞通知攔截請求,判斷該方法是否有自定義註解,而後判斷該用戶是否有該權限。這裏作的比較簡單,只有兩個權限:一個普通用戶、一個管理員。spring

項目搭建

這裏是基於SpringBoot的,對於SpringBoot項目的搭建就不說了。在項目中添加AOP的依賴:<!--more--->spring-boot

<!--AOP包-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

自定義註解及解析

在方法上添加該註解,說明該方法須要管理員權限才能訪問。code

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

      String authorities() default "ADMIN";

}

解析類:經過AOP的環繞通知獲取方法上的註解,判斷是否有Permission註解,返回註解的值。blog

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();
            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既可get

相關文章
相關標籤/搜索