springAop实现简单的权限角色验证

有时候项目比较简单,权限角色也比较简单,而且,角色是固定死的,由于公司项目不方便透露,就拿A,B两个角色来使用springAop完成权限认证好了.当然,我们必须知道登录用户的权限,因为项目比较简单,就把当前登录的角色信息扔session里面了,当然可以扩展,放redis里面,token里面信息等等等等…

使用场景

简单的项目,简单的权限验证,已知角色,角色固定等等一系列简单操作,只能判断角色是否符合
具体使用,还需要斟酌…

完成功能

使用注解的方式,完成权限认证,注解可以加在方法,或者类上,验证首先验证方法,在判断类上注解.如果方法上注解符合,则可以进行访问,如果方法上面没有对应注解,则判断类上面注解.如果角色符合则可以请求.

创建注解和切面

首先创建一个MyPermission注解:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyPermission {

    /**
     * 角色枚举
     * @author stack
     *
     */
    public enum Role{ A,B};

    Role needRole() default Role.A;

}

然后创个切面MyPermissionAspect:


@Aspect
@Component
@Slf4j
public class MyPermissionAspect {

    @Pointcut("@annotation(com.mr.web.annotation.MyPermission)")
    public void logPointCut() {
    }

    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {

        Object target = joinPoint.getTarget();
        String methodName = joinPoint.getSignature().getName();
        Class<?>[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getMethod().getParameterTypes();
        Method method = target.getClass().getMethod(methodName, parameterTypes);
        MyPermission methodAnnotation = method.getAnnotation(MyPermission.class);
        if (methodAnnotation != null) {
            MyPermission.Role methodPer = methodAnnotation.needRole();
            System.err.println("请求的方法上面的注解:" + methodPer);

            //从session或者缓存中取出用户的角色信息,进行对比,,如果不符合返回权限不足

        }


        MyPermission classAnnotation = target.getClass().getAnnotation(MyPermission.class);
        if (classAnnotation != null) {
            MyPermission.Role classPer = classAnnotation.needRole();
            System.err.println("请求的类上面的注解:" + classPer);

            //从session或者缓存中取出用户的角色信息,进行对比,,如果不符合返回权限不足


        }


    }

}

源码

https://github.com/stackXu/springboot-myProject

猜你喜欢

转载自blog.csdn.net/qq_38366063/article/details/92839824
今日推荐