zoukankan      html  css  js  c++  java
  • 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

    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    致虚极守静笃
    DNS 透明代理
    Java“禁止”泛型数组
    Java和C#语法对比
    JVM 内存区域 (运行时数据区域)
    Java8 使用
    G1收集器的收集原理
    BZOJ 2222: [Cqoi2006]猜数游戏【神奇的做法,傻逼题,猜结论】
    数据结构之网络流入门(Network Flow)简单小节
    BZOJ 1257: [CQOI2007]余数之和sum【神奇的做法,思维题】
  • 原文地址:https://www.cnblogs.com/javayida/p/13346942.html
Copyright © 2011-2022 走看看