shiro授权源码

在spring配置文件中开启shiro注解

  1. <!-- 开启shiro注解支持-->   
  2.     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
  3.         <property name="securityManager" ref="securityManager"/>  
  4.     </bean> 

     uthorizationAttributeSourceAdvisor类继承了StaticMethodMatcherPointcutAdvisor类,是spring AOP的一种方式

  1. public class AuthorizationAttributeSourceAdvisor extends StaticMethodMatcherPointcutAdvisor {  
  2.   
  3.     private static final Logger log = LoggerFactory.getLogger(AuthorizationAttributeSourceAdvisor.class);  
  4.   
  5.     private static final Class<? extends Annotation>[] AUTHZ_ANNOTATION_CLASSES =  
  6.             new Class[] {  
  7.                     RequiresPermissions.class, RequiresRoles.class,  
  8.                     RequiresUser.class, RequiresGuest.class, RequiresAuthentication.class  
  9.             };  
  10.   
  11.     protected SecurityManager securityManager = null;  
  12.   
  13.     /** 
  14.      * Create a new AuthorizationAttributeSourceAdvisor. 
  15.      */  
  16.     public AuthorizationAttributeSourceAdvisor() {  
  17.         setAdvice(new AopAllianceAnnotationsAuthorizingMethodInterceptor());  
  18.     }  

      

     初始化构造函数事调用setAdvice,参数传入了匿名内部类(AopAllianceAnnotationsAuthorizingMethodInterceptor

  1. public AopAllianceAnnotationsAuthorizingMethodInterceptor() {  
  2.         List<AuthorizingAnnotationMethodInterceptor> interceptors =  
  3.                 new ArrayList<AuthorizingAnnotationMethodInterceptor>(5);  
  4.         AnnotationResolver resolver = new SpringAnnotationResolver();  
  5.         //we can re-use the same resolver instance - it does not retain state:  
  6.         interceptors.add(new RoleAnnotationMethodInterceptor(resolver));  
  7.         interceptors.add(new PermissionAnnotationMethodInterceptorresolver));  

      interceptors集合中添加PermissionAnnotationMethodInterceptor

  1. public PermissionAnnotationMethodInterceptor(AnnotationResolver resolver) {  
  2.         supernew PermissionAnnotationHandler(), resolver);  

   调用父类AuthorizingAnnotationMethodInterceptor的构造方法,传了了权限注解处理类、注解解析器,看父类中AOP执行的方法invoke()
  1. public Object invoke(MethodInvocation methodInvocation) throws Throwable {  
  2.         assertAuthorized(methodInvocation);  
  3.         return methodInvocation.proceed();  
  4.     }  

   invoke()方法中调用assertAuthorized()方法
  1. public void assertAuthorized(MethodInvocation mi) throws AuthorizationException {  
  2.        try {  
  3.            ((AuthorizingAnnotationHandler)getHandler()).assertAuthorized(getAnnotation(mi));  
  4.        }  
  5.        catch(AuthorizationException ae) {  
  6.            // Annotation handler doesn't know why it was called, so add the information here if possible.   
  7.            // Don't wrap the exception here since we don't want to mask the specific exception, such as   
  8.            // UnauthenticatedException etc.   
  9.            if (ae.getCause() == null{ 
  10.                ae.initCause(new AuthorizationException("Not authorized to invoke method: " + mi.getMethod()));  
  11.            }
  12.            throw ae;  
  13.        }           
  14.    }  

其中((AuthorizingAnnotationHandler)getHandler()).assertAuthorized(getAnnotation(mi)),这行代码实际就是调用之前传入的注解处理类中的assertAuthorized方法
查看PermissionAnnotationHandler的对应方法
  1. public void assertAuthorized(Annotation a) throws AuthorizationException {  
  2.         if (!(a instanceof RequiresPermissions)) return;  
  3.   
  4.         RequiresPermissions rpAnnotation = (RequiresPermissions) a;  
  5.         String[] perms = getAnnotationValue(a);  
  6.         Subject subject = getSubject();  
  7.   
  8.         if (perms.length == 1) {  
  9.             subject.checkPermission(perms[0]);  
  10.             return;  
  11.         }  
  12.         if (Logical.AND.equals(rpAnnotation.logical())) {  
  13.             getSubject().checkPermissions(perms);  
  14.             return;  
  15.         }  
  16.         if (Logical.OR.equals(rpAnnotation.logical())) {  
  17.             // Avoid processing exceptions unnecessarily - "delay" throwing the exception by calling hasRole first  
  18.             boolean hasAtLeastOnePermission = false;  
  19.             for (String permission : perms) if (getSubject().isPermitted(permission)) hasAtLeastOnePermission = true;  
  20.             // Cause the exception if none of the role match, note that the exception message will be a bit misleading  
  21.             if (!hasAtLeastOnePermission) getSubject().checkPermission(perms[0]);  
  22.               
  23.         }  
  24.     }  

   方法中调用subject.checkPermission(),实际调用实现类DelegatingSubject.checkPermission()
  1. public void checkPermission(String permission) throws AuthorizationException {  
  2.         assertAuthzCheckPossible();  
  3.         securityManager.checkPermission(getPrincipals(), permission);  
  4.     }

   assertAuthzCheckPossible()
   shiro授权源码

   securityManager.checkPermission(),实际调用ModularRealmAuthorizercheckPermission()
  1. public void checkPermission(PrincipalCollection principals, String permission) throws AuthorizationException {  
  2.        assertRealmsConfigured();  
  3.        if (!isPermitted(principals, permission)) {  
  4.            throw new UnauthorizedException("Subject does not have permission [" + permission + "]");  
  5.        }  
  6.    }

   assertRealmsConfigured()
   shiro授权源码

   isPermitted()
  1. public boolean isPermitted(PrincipalCollection principals, String permission) {  
  2.        assertRealmsConfigured();  
  3.        for (Realm realm : getRealms()) {  
  4.            if (!(realm instanceof Authorizer)) continue;  
  5.            if (((Authorizer) realm).isPermitted(principals, permission)) {  
  6.                return true;  
  7.            }  
  8.        }  
  9.        return false;  
  10.    }  

   接着调用authorizingRealm中的isPermitted()
  1. public boolean isPermitted(PrincipalCollection principals, Permission permission) {  
  2.        AuthorizationInfo info = getAuthorizationInfo(principals);  
  3.        return isPermitted(permission, info);  
  4.    }  

   getAuthorizationInfo(),先从缓存中获取AuthorizationInfo,没有就从自定以realm中的doGetAuthorizationInfo()中获取
  1. protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {  
  2.        ...
  3.        AuthorizationInfo info = null;  
  4.        ...
  5.        Cache<Object, AuthorizationInfo> cache = getAvailableAuthorizationCache();  
  6.        if (cache != null) {  
  7.            ...  
  8.            Object key = getAuthorizationCacheKey(principals);  
  9.            info = cache.get(key);  
  10.            if (log.isTraceEnabled()) {  
  11.                if (info == null) {  
  12.                    log.trace("No AuthorizationInfo found in cache for principals [" + principals + "]");  
  13.                } else {  
  14.                    log.trace("AuthorizationInfo found in cache for principals [" + principals + "]");  
  15.                }  
  16.            }  
  17.        }  
  18.   
  19.        if (info == null) {  
  20.            info = doGetAuthorizationInfo(principals);    
  21.            ...
  22.        }  
  23.        return info;  
  24.    }  

   返回AuthorizationInfo后调用isPermitted()比较权限字符串是否包含权限注解中的字符串
  1. protected boolean isPermitted(Permission permission, AuthorizationInfo info) {  
  2.        Collection<Permission> perms = getPermissions(info);  
  3.        if (perms != null && !perms.isEmpty()) {  
  4.            for (Permission perm : perms) {  
  5.                if (perm.implies(permission)) {  
  6.                    return true;  
  7.                }  
  8.            }  
  9.        }  
  10.        return false;  
  11.    } 

  通过AuthorizationInfo获取对应的权限集合
   shiro授权源码

     接着调用wildCardPermission中的方法implies()
  shiro授权源码

   校验失败抛出UnauthorizedException异常
      ModularRealmAuthorizer中的checkPermission()
  1. public void checkPermission(PrincipalCollection principals, String permission) throws AuthorizationException {  
  2.        assertRealmsConfigured();  
  3.        if (!isPermitted(principals, permission)) {  
  4.            throw new UnauthorizedException("Subject does not have permission [" + permission + "]");  
  5.        }  
  6.    }