apache shiro是一個安全認證框架,和spring security相比,在於他使用了比較簡潔易懂的認證和受權方式。其提供的native-session(即把用戶認證後的受權信息保存在其自身提供Session中)機制,這樣就能夠和HttpSession、EJB Session Bean的基於容器的Session脫耦,到和客戶端應用、Flex應用、遠程方法調用等均可以使用它來配置權限認證。 在exit-web-framework裏的vcs-admin例子用到該框架,具體使用說明能夠參考官方幫助文檔。在這裏主要講解如何與spring結合、動態建立filterchaindefinitions、以及認證、受權、和緩存處理。html
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:java
<!-- Spring ApplicationContext配置文件的路徑,可以使用通配符,多個路徑用,號分隔 此參數用於後面的Spring Context Loader --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:/applicationContext-shiro.xml </param-value> </context-param> <!-- shiro security filter --> <filter> <!-- 這裏的filter-name要和spring的applicationContext-shiro.xml裏的 org.apache.shiro.spring.web.ShiroFilterFactoryBean的bean name相同 --> <filter-name>shiroSecurityFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroSecurityFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
applicationContext-shiro.xml文件中,定義web支持的SecurityManager和"shiroSecurityFilter"bean將會被web.xml 引用。git
<bean id="shiroSecurityFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- shiro的核心安全接口 --> <property name="securityManager" ref="securityManager" /> <!-- 要求登陸時的連接 --> <property name="loginUrl" value="/login.jsp" /> <!-- 登錄成功後要跳轉的鏈接 --> <property name="successUrl" value="/index.jsp" /> <!-- 未受權時要跳轉的鏈接 --> <property name="unauthorizedUrl" value="/unauthorized.jsp" /> <!-- shiro鏈接約束配置 --> <propery name="filterChainDefinitions"> <value> /login = authc /logout = logout /resource/** = anon </value> </property> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
在獨立應用程序和Web應用程序中,你可能想爲安全檢查使用Shiro 的註釋(例如,@RequiresRoles,@RequiresPermissions 等等)。這須要Shiro 的Spring AOP 集成來掃描合適的註解類以及執行必要的安全邏輯。如下是如何使用這些註解的。只需添加這兩個bean:github
<bean class="org.springframwork.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean>
有時,在某些系統想經過讀取數據庫來定義org.apache.shiro.spring.web.ShiroFilterFactoryBean的filterChainDefinitions。這樣可以經過操做界面或者維護後臺來管理系統的連接。web
在shrio與spring集成好了之後,調試源碼的高人可能已經注意到。項目啓動時,shrio經過本身的org.apache.shiro.spring.web.ShiroFilterFactoryBean類的filterChainDefinitions(受權規則定義)屬性轉換爲一個filterChainDefinitionMap,轉換完成後交給ShiroFilterFactoryBean保管。ShiroFilterFactoryBean根據受權(AuthorizationInfo類)後的信息去判斷哪些連接能訪問哪些連接不能訪問。filterChainDefinitionMap裏面的鍵就是連接URL,值就是存在什麼條件才能訪問該連接,如perms、roles。filterChainDefinitionMap是一個Map,shiro擴展出一個Map的子類Ini.Sectionspring
如今有一張表的描述實體類,以及數據訪問:數據庫
@Entity @Table(name="TB_RESOURCE") public class Resource implements Serializable { //主鍵id @Id private String id; //action url private String value; //shiro permission; private String permission; //------------------Getter/Setter---------------------// }
@Repository public class ResourceDao extends BasicHibernateDao<Resource, String> { }
經過該類能夠知道permission字段和value就是filterChainDefinitionMap的鍵/值,用spring FactoryBean接口的實現getObject()返回Section給filterChainDefinitionMap便可apache
public class ChainDefinitionSectionMetaSource implements FactoryBean<Ini.Section>{ @Autowired private ResourceDao resourceDao; private String filterChainDefinitions; /** * 默認premission字符串 */ public static final String PREMISSION_STRING="perms[\"{0}\"]"; public Section getObject() throws BeansException { //獲取全部Resource List<Resource> list = resourceDao.getAll(); Ini ini = new Ini(); //加載默認的url ini.load(filterChainDefinitions); Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME); //循環Resource的url,逐個添加到section中。section就是filterChainDefinitionMap, //裏面的鍵就是連接URL,值就是存在什麼條件才能訪問該連接 for (Iterator<Resource> it = list.iterator(); it.hasNext();) { Resource resource = it.next(); //若是不爲空值添加到section中 if(StringUtils.isNotEmpty(resource.getValue()) && StringUtils.isNotEmpty(resource.getPermission())) { section.put(resource.getValue(), MessageFormat.format(PREMISSION_STRING,resource.getPermission())); } } return section; } /** * 經過filterChainDefinitions對默認的url過濾定義 * * @param filterChainDefinitions 默認的url過濾定義 */ public void setFilterChainDefinitions(String filterChainDefinitions) { this.filterChainDefinitions = filterChainDefinitions; } public Class<?> getObjectType() { return this.getClass(); } public boolean isSingleton() { return false; } }
定義好了chainDefinitionSectionMetaSource後修改applicationContext-shiro.xml文件緩存
<bean id="chainDefinitionSectionMetaSource" class="org.exitsoft.showcase.vcsadmin.service.account.ChainDefinitionSectionMetaSource"> <property name="filterChainDefinitions"> <value> /login = authc /logout = logout /resource/** = anon </value> </property> </bean> <bean id="shiroSecurityFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/login.jsp" /> <property name="successUrl" value="/index.jsp" /> <property name="unauthorizedUrl" value="/unauthorized.jsp" /> <!-- shiro鏈接約束配置,在這裏使用自定義的動態獲取資源類 --> <property name="filterChainDefinitionMap" ref="chainDefinitionSectionMetaSource" /> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
在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) 也知道如何協調多個後臺數據源來訪問角色惡化權限信息和準確地決定用戶是否被容許執行給定的動做。
簡單的一個用戶和一個資源實體:
@Entity @Table(name="TB_RESOURCE") public class Resource implements Serializable { //主鍵id @Id private String id; //action url private String value; //shiro permission; private String permission; //------------------Getter/Setter---------------------// }
@Entity @Table(name="TB_USER") @SuppressWarnings("serial") public class User implements Serializable { //主鍵id @Id private String id; //登陸名稱 private String username; //登陸密碼 private String password; //擁有能訪問的資源/連接() private List<Resource> resourcesList = new ArrayList<Resource>(); //-------------Getter/Setter-------------// }
@Repository public class UserDao extends BasicHibernateDao<User, String> { public User getUserByUsername(String username) { return findUniqueByProperty("username", username); } }
實現org.apache.shiro.realm.AuthorizingRealm中已經給出了兩個抽象方法:
public class ShiroDataBaseRealm extends AuthorizingRealm{ @Autowired private UserDao userDao; /** * * 當用戶進行訪問連接時的受權方法 * */ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { if (principals == null) { throw new AuthorizationException("Principal對象不能爲空"); } User user = (User) principals.fromRealm(getName()).iterator().next(); //獲取用戶響應的permission List<String> permissions = CollectionUtils.extractToList(user.getResourcesList(), "permission",true); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.addStringPermissions(permissions); return info; } /** * 用戶登陸的認證方法 * */ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; String username = usernamePasswordToken.getUsername(); if (username == null) { throw new AccountException("用戶名不能爲空"); } User user = userDao.getUserByUsername(username); if (user == null) { throw new UnknownAccountException("用戶不存在"); } return new SimpleAuthenticationInfo(user,user.getPassword(),getName()); } }
定義好了ShiroDataBaseRealm後修改applicationContext-shiro.xml文件
<bean id="chainDefinitionSectionMetaSource" class="org.exitsoft.showcase.vcsadmin.service.account.ChainDefinitionSectionMetaSource"> <property name="filterChainDefinitions"> <value> /login = authc /logout = logout /resource/** = anon </value> </property> </bean> <bean id="shiroSecurityFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/login.jsp" /> <property name="successUrl" value="/index.jsp" /> <property name="unauthorizedUrl" value="/unauthorized.jsp" /> <!-- shiro鏈接約束配置,在這裏使用自定義的動態獲取資源類 --> <property name="filterChainDefinitionMap" ref="chainDefinitionSectionMetaSource" /> </bean> <bean id="shiroDataBaseRealm" class="org.exitsoft.showcase.vcsadmin.service.account.ShiroDataBaseRealm"> <!-- MD5加密 --> <property name="credentialsMatcher"> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <property name="hashAlgorithmName" value="MD5" /> </bean> </property> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="shiroDataBaseRealm" /> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
shiro CacheManager建立並管理其餘Shiro組件使用的Cache實例生命週期。由於Shiro可以訪問許多後臺數據源,如:身份驗證,受權和會話管理,緩存在框架中一直是一流的架構功能,用來在同時使用這些數據源時提升性能。任何現代開源和/或企業的緩存產品可以被插入到Shiro 來提供一個快速及高效的用戶體驗。
自從spring 3.1問世後推出了緩存功能後,提供了對已有的 Spring 應用增長緩存的支持,這個特性對應用自己來講是透明的,經過緩存抽象層,使得對已有代碼的影響下降到最小。
該緩存機制針對於 Java 的方法,經過給定的一些參數來檢查方法是否已經執行,Spring 將對執行結果進行緩存,而無需再次執行方法。
可經過下列配置來啓用緩存的支持:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <!-- 使用緩存annotation 配置 --> <cache:annotation-driven cache-manager="ehCacheManager" /> </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文件添加緩存
<bean id="chainDefinitionSectionMetaSource" class="org.exitsoft.showcase.vcsadmin.service.account.ChainDefinitionSectionMetaSource"> <property name="filterChainDefinitions" > <value> /login = authc /logout = logout /resource/** = anon </value> </property> </bean> <bean id="shiroSecurityFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/login.jsp" /> <property name="successUrl" value="/index.jsp" /> <property name="unauthorizedUrl" value="/unauthorized.jsp" /> <!-- shiro鏈接約束配置,在這裏使用自定義的動態獲取資源類 --> <property name="filterChainDefinitionMap" ref="chainDefinitionSectionMetaSource" /> </bean> <bean id="shiroDataBaseRealm" class="org.exitsoft.showcase.vcsadmin.service.account.ShiroDataBaseRealm"> <!-- MD5加密 --> <property name="credentialsMatcher"> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <property name="hashAlgorithmName" value="MD5" /> </bean> </property> <property name="authorizationCacheName" value="shiroAuthorizationCache" /> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="shiroDataBaseRealm" /> <property name="cacheManager" ref="cacheManager" /> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- 使用緩存annotation 配置 --/> <cache:annotation-driven cache-manager="ehCacheManager" /> <!-- spring對ehcache的緩存工廠支持 --> <bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache.xml" /> <property name="shared" value="false" /> </bean> <!-- spring對ehcache的緩存管理 --> <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="ehCacheManagerFactory"></property> </bean> <!-- shiro對ehcache的緩存管理直接使用spring的緩存工廠 --> <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManager" ref="ehCacheManagerFactory" /> </bean>
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <!-- maxElementsInMemory爲緩存對象的最大數目, eternal設置是否永遠不過時, timeToIdleSeconds對象處於空閒狀態的最多秒數, timeToLiveSeconds對象處於緩存狀態的最多秒數 --> <diskStore path="java.io.tmpdir"/> <cache name="shiroAuthorizationCache" maxElementsInMemory="300" eternal="false" timeToLiveSeconds="600" overflowToDisk="false"/> </ehcache>
public class UserDao extends BasicHibernateDao<User, String> { public User getUserByUsername(String username) { return findUniqueByProperty("username", username); } @CacheEvict(value="shiroAuthorizationCache",allEntries=true) public void saveUser(User entity) { save(entity); } }
@Repository public class ResourceDao extends BasicHibernateDao<Resource, String> { @CacheEvict(value="shiroAuthorizationCache",allEntries=true) public void saveResource(Resource entity) { save(entity); } @CacheEvict(value="shiroAuthorizationCache",allEntries=true) public void deleteResource(Resource entity) { delete(entity); } }
當userDao或者reaourceDao調用了相應帶有緩存註解的方法,都會將AuthorizingRealm類中的緩存去掉。那麼就意味着 shiro在用戶訪問連接時要從新受權一次。
整個apache shiro的使用在basic-curd項目有例子。能夠參考showcase/basic-curd項目中的例子去理解。。