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()
   

   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()
   

   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获取对应的权限集合
   

     接着调用wildCardPermission中的方法implies()
  

   校验失败抛出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.    } 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Shiro是一个开源的Java安全框架,用于对应用程序进行身份验证、授权和加密等安全相关功能的支持。Spring Boot是一个用于创建独立的、生产级别的Spring应用程序的框架。 Shiro Spring Boot Starter是一个与Spring Boot集成的项目,它提供了使用Shiro框架进行身份验证和授权的便捷方式。通过引入Shiro Spring Boot Starter依赖,可以轻松将Shiro集成到Spring Boot应用程序中。 Shiro Spring Boot Starter的源码包括几个主要部分: 1. 自动配置类:ShiroAutoConfiguration是Shiro Spring Boot Starter的核心配置类,它通过@EnableConfigurationProperties注解读取配置文件中的属性,并根据这些属性进行相应的自动配置。它负责创建Shiro的安全管理器、认证器、授权器等实例,并通过注入的方式将它们注入到Spring容器中。 2. 属性配置类:ShiroProperties定义了Shiro在配置文件中的属性,并提供了默认值。通过@ConfigurationProperties注解,可以将这些属性与配置文件中的对应属性进行关联。 3. 注解支持类:ShiroAnnotationProcessor是一个自定义的注解处理器,它通过处理标注了@RequiresAuthentication、@RequiresUser、@RequiresRoles和@RequiresPermissions等注解的方法,实现了对方法级别的身份验证和授权支持。 4. 过滤器类:ShiroFilterChainDefinition是Shiro的过滤器链定义类,它定义了URL与过滤器的映射关系,并负责创建ShiroFilterFactoryBean的实例,将其注入到容器中。 5. 辅助类:ShiroUtils是一个工具类,提供了一些常用的方法,如获取当前登录用户的主体、判断用户是否拥有指定角色或权限等。 总的来说,Shiro Spring Boot Starter的源码实现了对Shiro框架在Spring Boot应用程序中的集成和自动配置。通过引入该Starter依赖,可以简化Shiro框架的配置和使用,提高开发效率,同时保证应用程序的安全性。 ### 回答2: Shiro是一个基于Java的开源安全框架,用于提供身份验证、授权、会话管理和密码加密等功能。它能帮助开发人员快速构建安全可靠的应用程序。而Spring Boot是一个基于Spring框架的开源项目,它简化了Spring应用程序的开发和部署。 Shiro和Spring Boot结合使用,可以使得应用程序的安全性和性能得到更好地保障。Shiro作为一个独立的框架可以和Spring Boot集成,通过配置文件和注解的方式,实现对应用程序的安全管理。 Shiro Spring Boot源码是指将Shiro和Spring Boot集成时所使用到的相关源代码。这些源码包括了配置文件、注解、代码注入、过滤器等等。通过阅读和理解这些源码,开发人员可以深入了解Shiro Spring Boot集成的工作原理和机制。 通过阅读Shiro Spring Boot源码,我们可以了解到Shiro是如何通过自定义配置文件和注解来实现各种身份验证和授权的方式。源码中可以看到一些关键的类和方法,如Realm、Subject、AuthenticationToken等等,这些类和方法对于理解Shiro Spring Boot的工作流程非常重要。 另外,Shiro Spring Boot源码还涉及到了Spring Boot的自动配置机制。Spring Boot通过自动配置,可以减少开发人员的工作量,自动完成一些基本的配置,以适应不同的应用需求。通过阅读源码,我们可以了解到Spring Boot是如何实现自动配置功能的,以及如何自定义配置来适配特定的应用场景。 总的来说,阅读Shiro Spring Boot源码有助于我们深入理解Shiro和Spring Boot的工作原理和机制,提升对应用程序的安全性和性能的把握,进而能更好地开发和调优应用程序。 ### 回答3: Shiro是一个强大的身份认证和授权框架,而Spring Boot是一个用来简化Spring应用程序开发和部署的框架。Shiro Spring Boot是Shiro和Spring Boot的结合体,提供了在Spring Boot应用中集成Shiro的功能。 Shiro Spring Boot源码包含了一系列的类和配置文件,用于配置和启动Shiro框架。在源码中,可以找到一些核心类,比如ShiroFilterFactoryBean、DefaultWebSecurityManager等。这些类负责处理Shiro的配置和初始化。 ShiroFilterFactoryBean是Shiro的核心过滤器,是Shiro的入口点。它负责创建Shiro的安全过滤器链,并根据配置决定哪些请求应该经过Shiro的认证和授权。 DefaultWebSecurityManager是Shiro的安全管理器,它负责管理和协调Shiro的各种组件,比如Realm、SessionManager等。它是Shiro框架中最重要的组件之一。 除了这些核心类,源码中还包含了一些配置类,比如ShiroConfig、ShiroProperties等,用于配置Shiro的相关参数和属性。这些配置类提供了灵活的配置选项,使用户可以根据自己的需求来定制Shiro的行为。 总的来说,Shiro Spring Boot源码提供了一个方便快捷地在Spring Boot应用中集成Shiro的方式。通过深入研究和理解源码,我们可以更好地掌握Shiro的工作原理,并根据自己的需求进行扩展和定制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值