SpringBoot 自定義註解實現權限控制

Spring 自定義註解和實現,基於aop實現,實現一個權限控制的自定義註解

實現權限控制可以選擇shiro,但是覺得shiro很重,不需要使用到,也可以用springBoot的aop方式實現自定義註解

1.先定義一個自定義註解

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PermissionNeed {
    String value() default "";
}
2.aop的使用

@Aspect
@Component
public class LovePiAspect {

    @Pointcut("@annotation(permissionNeed)")
    public  void annotationPointCut(PermissionNeed permissionNeed) {

    }

    @Before("annotationPointCut(permissionNeed)")
    public void before(JoinPoint joinPoint,PermissionNeed permissionNeed){
        MapperMethod.MethodSignature sign =  (MapperMethod.MethodSignature)joinPoint.getSignature();
        System.out.print("接受方法:"+" 前置日誌");
        String permission = permissionNeed.value();
        //權限控制業務
        //擁有的權限
        Set<String> userPrivilegeSet = OAuthUserContext.getUserPrivilegeSet();
        //單個或者多個,分割符啥的可以自己定義
        if(!userPrivilegeSet.contains(permission)){
            throw new AppException(ApiResponseCode.PROMPT.get(),"該功能暫時不對您開放哦");
        }
    }

}
userPrivailegeSet可以在每次請求或者登錄時候,獲取到全部的權限,使用threadLocal作爲線程保存。權限不滿足,拋出自定義的異常

3.使用自定義註解

    @ResponseBody
    @RequestMapping(value = "/",method = RequestMethod.GET)
    @PermissionNeed(value = "sys:user:login")
    public String home() {
        return "Hello World!";
    }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章