shiro學習(6)-ssm整合-授權+緩存

授權具體實現

授權

	/**
	 * 授權
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//從認證器中得到CurrentUser對象
		CurrentUser user = (CurrentUser)principals.getPrimaryPrincipal();
		//通過用戶ID查詢到對應的權限表示符
		List<String> userPermission = userDao.findUserPermissions(user.getUserid());
		//將list轉爲set
		Set<String> set = new HashSet<String>();
		for(String c : userPermission){
			if(c!=null && !("".equals(c))){
				set.add(c);
			}
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addStringPermissions(set);
		System.out.println("=====================================================>>>>>>>>>>");
		return info;
	}

授權配置

   在SpringMVC的配置文件中開啓shiro註解

添加依賴


<!-- Aop -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.7</version>
</dependency>

<!-- shiro整合ehcache緩存管理器 -->

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-ehcache</artifactId>
    <version>1.3.1</version>
</dependency>

springMVC配置文件

  <!-- 基於註解權限控制  基於類的代理  -->
     <aop:config proxy-target-class="true"></aop:config>

spring-shiro.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true" 
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
	http://www.springframework.org/schema/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!-- 配置web.xml中過濾器對應的spring容器的bean -->
	<bean id="shiro" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" >
		<!-- 註冊SecurityManager  -->
		<property name="securityManager" ref="securityManager"></property>
		<!-- 登錄時訪問的鏈接 -->
		<property name="loginUrl" value="/loginUI"></property>
		<!-- 用戶無權限時需要訪問的頁面 -->
		<property name="unauthorizedUrl" value="/errorUI"></property>
		<!-- 設置 過濾器鏈 -->
		<property name="filterChainDefinitions">
			<value>
				/bootstrap/** = anon
				/dist/** = anon
				/images/** = anon
				/jquery/** = anon
				/tzms/** = anon
				<!-- 所有請求匿名訪問  /** = anon -->
				<!-- 點擊登錄 不需要認證 -->
				/login = anon
				<!-- 退出 此方法會清空shiro中session的數據 -->
				/logout = logout
				<!-- 所有的url都必須要認證通過後纔可以訪問 -->
				/** = authc
			</value>
		</property>
	</bean>
	
	<!-- 配置安全管理器對象 -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<!-- 配置自定義數據源 -->
		<property name="realm" ref="shiroUserRealm"></property>
		<!-- 配置緩存 -->
		<property name="cacheManager" ref="ehCacheManager"></property>
	</bean>
	
	<!-- 配置自定義Realm -->
	<bean id="shiroUserRealm" class="com.tanzhou.tzms.common.service.impl.ShiroRealmsOne">
		<!-- 配置憑證匹配器 -->
		<property name="credentialsMatcher" ref="credentialsMatcher"></property>
	</bean>
	
	<!-- 定義憑證匹配器 -->
	<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
		<!-- 匹配散列算法 -->
		<property name="hashAlgorithmName" value="MD5"></property>
		<!-- 匹配散列次數 -->
		<property name="hashIterations" value="1"></property>
	</bean>
	
	<bean id="advisor" class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
		<property name="securityManager" ref="securityManager"></property>
	</bean>
	
	<!-- 配置緩存管理器 -->
	<bean id="ehCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
		<!-- 配置緩存管理文件 -->
		<property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"></property>
	 </bean>
</beans>

shrio-ehcache.xml緩存配置文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <!--
       diskStore:爲緩存路徑,ehcache分爲內存和磁盤兩級,
       	此屬性定義磁盤的緩存位置。參數解釋如下:
     -->
    <diskStore path="F:\ehcache"/>
    <!--
       defaultCache:默認緩存策略
     -->
    <!--
      maxElementsInMemory:緩存最大數目
      maxElementsOnDisk:硬盤最大緩存個數。
      eternal:對象是否永久有效,一但設置了,timeout將不起作用。
      overflowToDisk:是否保存到磁盤,當系統當機時
      timeToIdleSeconds:設置對象在失效前的允許閒置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閒置時間無窮大。
      timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介於創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。
      diskPersistent:是否緩存虛擬機重啓期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
      diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩衝區。
      diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。
      memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置爲FIFO(先進先出)或是LFU(較少使用)。
      clearOnFlush:內存數量最大時是否清除。
      memoryStoreEvictionPolicy:可選策略有:LRU(最近最少使用,默認策略)、FIFO(先進先出)、LFU(最少訪問次數)。
      FIFO,first in first out,這個是大家最熟的,先進先出。
      LFU, Less Frequently Used,就是上面例子中使用的策略,直白一點就是講一直以來最少被使用的。如上面所講,緩存的元素有一個hit屬性,hit值最小的將會被清出緩存。
      LRU,Least Recently Used,最近最少使用的,緩存的元素有一個時間戳,當緩存容量滿了,而又需要騰出地方來緩存新的元素的時候,那麼現有緩存元素中時間戳離當前時間最遠的元素將被清出緩存。
   -->
    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="true"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"/>
</ehcache>

基於註解式資源授權驗證

清空緩存

在自定義Realm中添加清空方法

/**
 * 清空緩存
 */
public void clearCache(){
	PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
	super.clearCache(principals);
}

添加業務處理方法

 第一次正常請求會授權,之後訪問從緩存中獲取。當調用清空緩存方法後,再次請求的時候因爲緩存已經空了,所以會再次授權,
  場景: 權限修改生效後,立即刷新清空緩存,則可以實現用戶不退出生效新的權限

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章