apache shiro与spring整合、动态filterChainDefinitions、以及认证、授权

2 篇文章 0 订阅

apache shiro是一个安全认证框架,和spring security相比,在于他使用了比较简洁易懂的认证和授权方式。其提供的native-session(即把用户认证后的授权信息保存在其自身提供Session中)机制,这样就可以和HttpSession、EJB Session Bean的基于容器的Session脱耦,到和客户端应用、Flex应用、远程方法调用等都可以使用它来配置权限认证。 在exit-web-framework里的vcs-admin例子用到该框架,具体使用说明可以参考官方帮助文档。在这里主要讲解如何与spring结合、动态创建filterchaindefinitions、以及认证、授权、和缓存处理。

apache shiro 结合spring

Shiro 拥有对Spring Web 应用程序的一流支持。在Web 应用程序中,所有Shiro 可访问的万恶不请求必须通过一个主要的Shiro 过滤器。该过滤器本身是极为强大的,允许临时的自定义过滤器链基于任何URL 路径表达式执行。 在Shiro 1.0 之前,你不得不在Spring web 应用程序中使用一个混合的方式,来定义Shiro 过滤器及所有它在web.xml中的配置属性,但在Spring XML 中定义SecurityManager。这有些令人沮丧,由于你不能把你的配置固定在一个地方,以及利用更为先进的Spring 功能的配置能力,如PropertyPlaceholderConfigurer 或抽象bean 来固定通用配置。现在在Shiro 1.0 及以后版本中,所有Shiro 配置都是在Spring XML 中完成的,用来提供更为强健的Spring 配置机制。以下是如何在基于Spring web 应用程序中配置Shiro: web.xml:

  1. <!-- Spring ApplicationContext配置文件的路径,可使用通配符,多个路径用,号分隔 此参数用于后面的Spring Context Loader --> 
  2. <context-param> 
  3.     <param-name>contextConfigLocation</param-name> 
  4.     <param-value> 
  5.         classpath*:/applicationContext-shiro.xml  
  6.     </param-value> 
  7. </context-param> 
  8.  
  9. <!-- shiro security filter --> 
  10. <filter> 
  11.     <!-- 这里的filter-name要和spring的applicationContext-shiro.xml里的  
  12.             org.apache.shiro.spring.web.ShiroFilterFactoryBean的bean name相同 --> 
  13.     <filter-name>shiroSecurityFilter</filter-name> 
  14.     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
  15.     <init-param> 
  16.         <param-name>targetFilterLifecycle</param-name> 
  17.         <param-value>true</param-value> 
  18.     </init-param> 
  19. </filter> 
  20.  
  21. <filter-mapping> 
  22.     <filter-name>shiroSecurityFilter</filter-name> 
  23.     <url-pattern>/*</url-pattern> 
  24. </filter-mapping> 
applicationContext-shiro.xml文件中,定义web支持的SecurityManager和"shiroSecurityFilter"bean将会被web.xml 引用。
  1. <bean id="shiroSecurityFilter"> 
  2.     <!-- shiro的核心安全接口 --> 
  3.     <property name="securityManager" ref="securityManager" /> 
  4.     <!-- 要求登录时的链接 --> 
  5.     <property name="loginUrl" value="/login.jsp" /> 
  6.     <!-- 登陆成功后要跳转的连接 --> 
  7.     <property name="successUrl" value="/index.jsp" /> 
  8.     <!-- 未授权时要跳转的连接 --> 
  9.     <property name="unauthorizedUrl" value="/unauthorized.jsp" /> 
  10.     <!-- shiro连接约束配置 --> 
  11.     <property name="filterChainDefinitions"> 
  12.         <value> 
  13.             /login = authc 
  14.             /logoutlogout = logout  
  15.             /resource/** = anon  
  16.         </value> 
  17.     </property> 
  18. </bean> 
  19.  
  20. <bean id="securityManager"> 
  21. </bean> 
  22.  
  23. <bean id="lifecycleBeanPostProcessor"/> 
启用Shiro注解

在独立应用程序和Web应用程序中,你可能想为安全检查使用Shiro 的注释(例如,@RequiresRoles,@RequiresPermissions 等等)。这需要Shiro 的Spring AOP 集成来扫描合适的注解类以及执行必要的安全逻辑。以下是如何使用这些注解的。只需添加这两个bean 定义到applicationContext-shiro.xml 中:

  1. <bean depends-on="lifecycleBeanPostProcessor"/> 
  2.  
  3. <bean> 
  4.     <property name="securityManager" ref="securityManager"/> 
  5. </bean> 
动态创建filterchaindefinitions

有时,在某些系统想通过读取数据库来定义org.apache.shiro.spring.web.ShiroFilterFactoryBean的filterChainDefinitions。这样能够通过操作界面或者维护后台来管理系统的链接。

在shrio与spring集成好了以后,调试源码的高人可能已经注意到。项目启动时,shrio通过自己的org.apache.shiro.spring.web.ShiroFilterFactoryBean类的filterChainDefinitions(授权规则定义)属性转换为一个filterChainDefinitionMap,转换完成后交给ShiroFilterFactoryBean保管。ShiroFilterFactoryBean根据授权(AuthorizationInfo类)后的信息去判断哪些链接能访问哪些链接不能访问。filterChainDefinitionMap里面的键就是链接URL,值就是存在什么条件才能访问该链接,如perms、roles。filterChainDefinitionMap是一个Map,shiro扩展出一个Map的子类Ini.Section

现在有一张表的描述实体类,以及数据访问:

  1. @Entity  
  2. @Table(name="TB_RESOURCE")  
  3. public class Resource implements Serializable {  
  4.     //主键id  
  5.     @Id  
  6.     private String id;  
  7.     //action url  
  8.     private String value;  
  9.     //shiro permission;  
  10.     private String permission;  
  11.     //------------------Getter/Setter---------------------//  
  12. }  

  1. @Repository  
  2. public class ResourceDao extends BasicHibernateDao<Resource, String> {  
  3.  
  4. }  

通过该类可以知道permission字段和value就是filterChainDefinitionMap的键/值,用springFactoryBean接口的实现getObject()返回Section给filterChainDefinitionMap即可

  1. public class ChainDefinitionSectionMetaSource implements FactoryBean<Ini.Section>{  
  2.  
  3.     @Autowired  
  4.     private ResourceDao resourceDao;  
  5.  
  6.     private String filterChainDefinitions;  
  7.  
  8.     /**
  9.      * 默认premission字符串  
  10.      */ 
  11.     public static final String PREMISSION_STRING="perms[\"{0}\"]";  
  12.  
  13.     public Section getObject() throws BeansException {  
  14.  
  15.         //获取所有Resource  
  16.         List<Resource> list = resourceDao.getAll();  
  17.  
  18.         Ini ini = new Ini();  
  19.         //加载默认的url  
  20.         ini.load(filterChainDefinitions);  
  21.         Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);  
  22.         //循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap,  
  23.         //里面的键就是链接URL,值就是存在什么条件才能访问该链接  
  24.         for (Iterator<Resource> it = list.iterator(); it.hasNext();) {  
  25.  
  26.             Resource resource = it.next();  
  27.             //如果不为空值添加到section中  
  28.             if(StringUtils.isNotEmpty(resource.getValue()) && StringUtils.isNotEmpty(resource.getPermission())) {  
  29.                 section.put(resource.getValue(),  MessageFormat.format(PREMISSION_STRING,resource.getPermission()));  
  30.             }  
  31.  
  32.         }  
  33.  
  34.         return section;  
  35.     }  
  36.  
  37.     /**
  38.      * 通过filterChainDefinitions对默认的url过滤定义  
  39.      *   
  40.      * @param filterChainDefinitions 默认的url过滤定义  
  41.      */ 
  42.     public void setFilterChainDefinitions(String filterChainDefinitions) {  
  43.         this.filterChainDefinitions = filterChainDefinitions;  
  44.     }  
  45.  
  46.     public Class<?> getObjectType() {  
  47.         return this.getClass();  
  48.     }  
  49.  
  50.     public boolean isSingleton() {  
  51.         return false;  
  52.     }  
  53.  
  54. }  
定义好了chainDefinitionSectionMetaSource后修改applicationContext-shiro.xml文件
  1. <bean id="chainDefinitionSectionMetaSource"> 
  2.  
  3.     <property name="filterChainDefinitions"> 
  4.         <value> 
  5.             /login = authc 
  6.             /logoutlogout = logout  
  7.             /resource/** = anon  
  8.         </value> 
  9.     </property> 
  10. </bean> 
  11.  
  12. <bean id="shiroSecurityFilter"> 
  13.     <property name="securityManager" ref="securityManager" /> 
  14.     <property name="loginUrl" value="/login.jsp" /> 
  15.     <property name="successUrl" value="/index.jsp" /> 
  16.     <property name="unauthorizedUrl" value="/unauthorized.jsp" /> 
  17.     <!-- shiro连接约束配置,在这里使用自定义的动态获取资源类 --> 
  18.     <property name="filterChainDefinitionMap" ref="chainDefinitionSectionMetaSource" /> 
  19. </bean> 
  20.  
  21. <bean id="securityManager"> 
  22. </bean> 
  23.  
  24. <bean id="lifecycleBeanPostProcessor"/> 
shiro数据库认证、授权

在shiro认证和授权主要是两个类,就是org.apache.shiro.authc.AuthenticationInfo和org.apache.shiro.authz.AuthorizationInfo。该两个类的处理在org.apache.shiro.realm.AuthorizingRealm中已经给出了两个抽象方法。就是:

/**
 * Retrieves the AuthorizationInfo for the given principals from the underlying data store.  When returning
 * an instance from this method, you might want to consider using an instance of
 * {@link org.apache.shiro.authz.SimpleAuthorizationInfo SimpleAuthorizationInfo}, as it is suitable in most cases.
 *
 * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
 * @return the AuthorizationInfo associated with this principals.
 * @see org.apache.shiro.authz.SimpleAuthorizationInfo
 */
protected abstract AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);

/**
 * Retrieves authentication data from an implementation-specific datasource (RDBMS, LDAP, etc) for the given
 * authentication token.
 * <p/>
 * For most datasources, this means just 'pulling' authentication data for an associated subject/user and nothing
 * more and letting Shiro do the rest.  But in some systems, this method could actually perform EIS specific
 * log-in logic in addition to just retrieving data - it is up to the Realm implementation.
 * <p/>
 * A {@code null} return value means that no account could be associated with the specified token.
 *
 * @param token the authentication token containing the user's principal and credentials.
 * @return an {@link AuthenticationInfo} object containing account data resulting from the
 *         authentication ONLY if the lookup is successful (i.e. account exists and is valid, etc.)
 * @throws AuthenticationException if there is an error acquiring data or performing
 *                                 realm-specific authentication logic for the specified <tt>token</tt>
 */
protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;

doGetAuthenticationInfo(AuthenticationToken token)(认证/登录方法)会返回一个AuthenticationInfo,就是认证信息。是一个对执行及对用户的身份验证(登录)尝试负责的方法。当一个用户尝试登录时,该逻辑被认证器执行。认证器知道如何与一个或多个Realm协调来存储相关的用户/帐户信息。从这些Realm中获得的数据被用来验证用户的身份来保证用户确实是他们所说的他们是谁。

doGetAuthorizationInfo(PrincipalCollection principals)是负责在应用程序中决定用户的访问控制的方法。它是一种最终判定用户是否被允许做某件事的机制。与doGetAuthenticationInfo(AuthenticationToken token)相似,doGetAuthorizationInfo(PrincipalCollection principals) 也知道如何协调多个后台数据源来访问角色恶化权限信息和准确地决定用户是否被允许执行给定的动作。

简单的一个用户和一个资源实体:

  1. @Entity  
  2. @Table(name="TB_RESOURCE")  
  3. public class Resource implements Serializable {  
  4.     //主键id  
  5.     @Id  
  6.     private String id;  
  7.     //action url  
  8.     private String value;  
  9.     //shiro permission;  
  10.     private String permission;  
  11.     //------------------Getter/Setter---------------------//  
  12. }  

  1. @Entity  
  2. @Table(name="TB_USER")  
  3. @SuppressWarnings("serial")  
  4. public class User implements Serializable {  
  5.     //主键id  
  6.     @Id  
  7.     private String id;  
  8.     //登录名称  
  9.     private String username;  
  10.     //登录密码  
  11.     private String password;  
  12.     //拥有能访问的资源/链接()  
  13.     private List<Resource> resourcesList = new ArrayList<Resource>();  
  14.     //-------------Getter/Setter-------------//  
  15. }  

  1. @Repository  
  2. public class UserDao extends BasicHibernateDao<User, String> {  
  3.  
  4.     public User getUserByUsername(String username) {  
  5.         return findUniqueByProperty("username", username);  
  6.     }  
  7.  
  8. }  

实现org.apache.shiro.realm.AuthorizingRealm中已经给出了两个抽象方法:

  1. public class ShiroDataBaseRealm extends AuthorizingRealm{  
  2.  
  3.     @Autowired  
  4.     private UserDao userDao;  
  5.  
  6.     /**
  7.      *   
  8.      * 当用户进行访问链接时的授权方法  
  9.      *   
  10.      */ 
  11.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  12.  
  13.         if (principals == null) {  
  14.             throw new AuthorizationException("Principal对象不能为空");  
  15.         }  
  16.  
  17.         User user = (User) principals.fromRealm(getName()).iterator().next();  
  18.  
  19.         //获取用户响应的permission  
  20.         List<String> permissions = CollectionUtils.extractToList(user.getResourcesList(), "permission",true);  
  21.  
  22.         SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
  23.  
  24.         info.addStringPermissions(permissions);  
  25.  
  26.         return info;  
  27.     }  
  28.  
  29.     /**
  30.      * 用户登录的认证方法  
  31.      *   
  32.      */ 
  33.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  
  34.         UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;  
  35.  
  36.         String username = usernamePasswordToken.getUsername();  
  37.  
  38.         if (username == null) {  
  39.             throw new AccountException("用户名不能为空");  
  40.         }  
  41.  
  42.         User user = userDao.getUserByUsername(username);  
  43.  
  44.         if (user == null) {  
  45.             throw new UnknownAccountException("用户不存在");  
  46.         }  
  47.  
  48.         return new SimpleAuthenticationInfo(user,user.getPassword(),getName());  
  49.     }  
  50. }  
定义好了ShiroDataBaseRealm后修改applicationContext-shiro.xml文件
  1. <bean id="chainDefinitionSectionMetaSource"> 
  2.  
  3.     <property name="filterChainDefinitions"> 
  4.         <value> 
  5.             /login = authc 
  6.             /logoutlogout = logout  
  7.             /resource/** = anon  
  8.         </value> 
  9.     </property> 
  10. </bean> 
  11.  
  12. <bean id="shiroSecurityFilter"> 
  13.     <property name="securityManager" ref="securityManager" /> 
  14.     <property name="loginUrl" value="/login.jsp" /> 
  15.     <property name="successUrl" value="/index.jsp" /> 
  16.     <property name="unauthorizedUrl" value="/unauthorized.jsp" /> 
  17.     <!-- shiro连接约束配置,在这里使用自定义的动态获取资源类 --> 
  18.     <property name="filterChainDefinitionMap" ref="chainDefinitionSectionMetaSource" /> 
  19. </bean> 
  20.  
  21. <bean id="shiroDataBaseRealm"> 
  22.     <!-- MD5加密 --> 
  23.     <property name="credentialsMatcher"> 
  24.         <bean> 
  25.             <property name="hashAlgorithmName" value="MD5" /> 
  26.         </bean> 
  27.     </property> 
  28. </bean> 
  29.  
  30. <bean id="securityManager"> 
  31.     <property name="realm" ref="shiroDataBaseRealm" /> 
  32. </bean> 
  33.  
  34. <bean id="lifecycleBeanPostProcessor"/> 
shiro EHcache 与 Spring EHcache集成

shiro CacheManager创建并管理其他Shiro组件使用的Cache实例生命周期。因为Shiro能够访问许多后台数据源,如:身份验证,授权和会话管理,缓存在框架中一直是一流的架构功能,用来在同时使用这些数据源时提高性能。任何现代开源和/或企业的缓存产品能够被插入到Shiro 来提供一个快速及高效的用户体验。

自从spring 3.1问世后推出了缓存功能后,提供了对已有的 Spring 应用增加缓存的支持,这个特性对应用本身来说是透明的,通过缓存抽象层,使得对已有代码的影响降低到最小。

该缓存机制针对于 Java 的方法,通过给定的一些参数来检查方法是否已经执行,Spring 将对执行结果进行缓存,而无需再次执行方法。

可通过下列配置来启用缓存的支持:

  1. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  2.   xmlns:cache="http://www.springframework.org/schema/cache" 
  3.    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  4.         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> 
  5.  
  6.     <!-- 使用缓存annotation 配置 --> 
  7.     <cache:annotation-driven cache-manager="ehCacheManager" /> 
  8.  
  9. </beans> 

@Cacheable**@CacheEvict**来对缓存进行操作

@Cacheable:负责将方法的返回值加入到缓存中

@CacheEvict:负责清除缓存

/**声明了一个名为 persons 的缓存区域,当调用该方法时,Spring 会检查缓存中是否存在 personId 对应的值。*/
@Cacheable("persons")
public Person profile(Long personId) { ... }

/**指定多个缓存区域。Spring 会一个个的检查,一旦某个区域存在指定值时则返回*/
@Cacheable({"persons", "profiles"})
public Person profile(Long personId) { ... }
</code>
</pre>

<pre>
<code>
/**清空所有缓存*/
@CacheEvict(value="persons",allEntries=true)
public Person profile(Long personId, Long groundId) { ... }

/**或者根据条件决定是否缓存*/
@CacheEvict(value="persons", condition="personId > 50")
public Person profile(Long personId) { ... }

在shiro里面会有授权缓存。可以通过AuthorizingRealm类中指定缓存名称。就是authorizationCacheName属性。当shiro为用户授权一次之后将会把所有授权信息都放进缓存中。现在有个需求。当在更新用户或者删除资源和更新资源的时候,要刷新一下shiro的授权缓存,给shiro重新授权一次。因为当更新用户或者资源时,很有可能已经把用户本身已有的资源去掉。不给用户访问。所以。借助spring的缓存工厂和shiro的缓存能够很好的实现这个需求。

将applicationContext-shiro.xml文件添加缓存

  1. <bean id="chainDefinitionSectionMetaSource"> 
  2.     <property name="filterChainDefinitions" > 
  3.         <value> 
  4.             /login = authc 
  5.             /logoutlogout = logout  
  6.             /resource/** = anon  
  7.         </value> 
  8.     </property> 
  9. </bean> 
  10.  
  11. <bean id="shiroSecurityFilter"> 
  12.     <property name="securityManager" ref="securityManager" /> 
  13.     <property name="loginUrl" value="/login.jsp" /> 
  14.     <property name="successUrl" value="/index.jsp" /> 
  15.     <property name="unauthorizedUrl" value="/unauthorized.jsp" /> 
  16.     <!-- shiro连接约束配置,在这里使用自定义的动态获取资源类 --> 
  17.     <property name="filterChainDefinitionMap" ref="chainDefinitionSectionMetaSource" /> 
  18. </bean> 
  19.  
  20. <bean id="shiroDataBaseRealm"> 
  21.     <!-- MD5加密 --> 
  22.     <property name="credentialsMatcher"> 
  23.         <bean> 
  24.             <property name="hashAlgorithmName" value="MD5" /> 
  25.         </bean> 
  26.     </property> 
  27.     <property name="authorizationCacheName" value="shiroAuthorizationCache" /> 
  28. </bean> 
  29.  
  30. <bean id="securityManager"> 
  31.     <property name="realm" ref="shiroDataBaseRealm" /> 
  32.     <property name="cacheManager" ref="cacheManager" /> 
  33. </bean> 
  34.  
  35. <bean id="lifecycleBeanPostProcessor"/> 
  36.  
  37. <!-- 使用缓存annotation 配置 --/> 
  38. <cache:annotation-driven cache-manager="ehCacheManager" /> 
  39.  
  40. <!-- spring对ehcache的缓存工厂支持 --> 
  41. <bean id="ehCacheManagerFactory"> 
  42.     <property name="configLocation" value="classpath:ehcache.xml" /> 
  43.     <property name="shared" value="false" /> 
  44. </bean> 
  45.  
  46. <!-- spring对ehcache的缓存管理 --> 
  47. <bean id="ehCacheManager"> 
  48.     <property name="cacheManager" ref="ehCacheManagerFactory"></property> 
  49. </bean> 
  50.  
  51. <!-- shiro对ehcache的缓存管理直接使用spring的缓存工厂 --> 
  52. <bean id="cacheManager">   
  53.     <property name="cacheManager" ref="ehCacheManagerFactory" /> 
  54. </bean> 
ehcache.xml
  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <ehcache>    
  3.     <!--  
  4.             maxElementsInMemory为缓存对象的最大数目,   
  5.             eternal设置是否永远不过期,  
  6.             timeToIdleSeconds对象处于空闲状态的最多秒数,  
  7.             timeToLiveSeconds对象处于缓存状态的最多秒数   
  8.      --> 
  9.     <diskStore path="java.io.tmpdir"/> 
  10.  
  11.     <cache name="shiroAuthorizationCache" maxElementsInMemory="300" eternal="false" timeToLiveSeconds="600" overflowToDisk="false"/> 
  12.  
  13. </ehcache> 

  1. public class UserDao extends BasicHibernateDao<User, String> {  
  2.  
  3.     public User getUserByUsername(String username) {  
  4.         return findUniqueByProperty("username", username);  
  5.     }  
  6.  
  7.     @CacheEvict(value="shiroAuthorizationCache",allEntries=true)  
  8.     public void saveUser(User entity) {  
  9.         save(entity);  
  10.     }  
  11.  
  12. }  


  1. @Repository  
  2. public class ResourceDao extends BasicHibernateDao<Resource, String> {  
  3.  
  4.     @CacheEvict(value="shiroAuthorizationCache",allEntries=true)  
  5.     public void saveResource(Resource entity) {  
  6.         save(entity);  
  7.     }  
  8.  
  9.     @CacheEvict(value="shiroAuthorizationCache",allEntries=true)  
  10.     public void deleteResource(Resource entity) {  
  11.         delete(entity);  
  12.     }  
 

当userDao或者reaourceDao调用了相应带有缓存注解的方法,都会将AuthorizingRealm类中的缓存去掉。那么就意味着 shiro在用户访问链接时要重新授权一次。

整个apache shiro的使用,vcs admin项目和vcs admin jpa中都会有例子。可以参考showcase/vcs_admin或者showcase/vcs_admin_jpa项目中的例子去理解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值