并发登录人数控制--Shiro系列(二)

为了安全起见,同一个账号理应同时只能在一台设备上登录,后面登录的踢出前面登录的。用Shiro可以轻松实现此功能。

shiro中sessionManager是专门作会话管理的,而sessinManager将会话保存在sessionDAO中,如果不给sessionManager注入

sessionDAO,会话将是瞬时状态,没有被保存起来,从sessionManager里取session,是取不到的。

此例中sessionDAO注入了Ehcache缓存,会话被保存在Ehcache中,不知Ehcache为何物的,请自行查阅资料。

完整demo下载:http://download.csdn.net/detail/qq_33556185/9555720

shiro.xml

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"  
  3.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans     
  5.     http://www.springframework.org/schema/beans/spring-beans-4.2.xsd     
  6.     http://www.springframework.org/schema/tx     
  7.     http://www.springframework.org/schema/tx/spring-tx-4.2.xsd    
  8.     http://www.springframework.org/schema/context    
  9.     http://www.springframework.org/schema/context/spring-context-4.2.xsd    
  10.     http://www.springframework.org/schema/mvc    
  11.     http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">  
  12.        
  13. <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">    
  14.         <property name="globalSessionTimeout" value="1800000"/>    
  15.         <property name="deleteInvalidSessions" value="true"/>    
  16.         <property name="sessionDAO" ref="sessionDAO"/>    
  17.         <property name="sessionIdCookieEnabled" value="true"/>    
  18.         <property name="sessionIdCookie" ref="sessionIdCookie"/>    
  19.         <property name="sessionValidationSchedulerEnabled" value="true"/>  
  20.         <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>  
  21.          <property name="cacheManager" ref="shiroEhcacheManager"/>  
  22. </bean>    
  23.        <!-- 会话DAO,sessionManager里面的session需要保存在会话Dao里,没有会话Dao,session是瞬时的,没法从  
  24.      sessionManager里面拿到session -->    
  25.     <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">    
  26.         <property name="sessionIdGenerator" ref="sessionIdGenerator"/>    
  27.         <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>  
  28.     </bean>   
  29.       <!-- 缓存管理器 -->  
  30.   <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">    
  31.   <property name="cacheManagerConfigFile" value="classpath:ehcache.xml" />    
  32.   </bean>  
  33. <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">    
  34.         <constructor-arg value="sid"/>  
  35.         <property name="httpOnly" value="true"/>  
  36.         <property name="maxAge" value="-1"/>   
  37. </bean>   
  38.  <!-- 会话ID生成器 -->  
  39.  <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"></bean>  
  40. <bean id="kickoutSessionControlFilter"  class="com.core.shiro.KickoutSessionControlFilter">    
  41.     <property name="sessionManager" ref="sessionManager"/>    
  42.     <property name="cacheManager" ref="shiroEhcacheManager"/>  
  43.     <property name="kickoutAfter" value="false"/>    
  44.     <property name="maxSession" value="1"/>    
  45.     <property name="kickoutUrl" value="/toLogin?kickout=1"/>    
  46. </bean>   
  47.       <bean id="logout" class="org.apache.shiro.web.filter.authc.LogoutFilter">  
  48.         <property name="redirectUrl" value="/toLogin" />  
  49.        </bean>   
  50.           <!-- 会话验证调度器 -->  
  51.     <bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler ">  
  52.         <property name="interval" value="1800000"/>  
  53.         <property name="sessionManager" ref="sessionManager"/>  
  54.     </bean>  
  55.      <!-- Shiro Filter 拦截器相关配置 -->    
  56.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">    
  57.         <!-- securityManager -->    
  58.         <property name="securityManager" ref="securityManager" />    
  59.         <!-- 登录路径 -->    
  60.         <property name="loginUrl" value="/toLogin" />    
  61.         <!-- 用户访问无权限的链接时跳转此页面  -->    
  62.         <property name="unauthorizedUrl" value="/unauthorizedUrl.jsp" />    
  63.          
  64.         <!-- 过滤链定义 -->    
  65.          <property name="filters">    
  66.          <map>    
  67.              <entry key="kickout" value-ref="kickoutSessionControlFilter"/>    
  68.          </map>    
  69.      </property>   
  70.         <property name="filterChainDefinitions">    
  71.             <value>    
  72.                 /loginin=kickout,anon  
  73.                  /logout = logout  
  74.                 /toLogin=anon  
  75.                 /css/**=anon   
  76.                 /html/**=anon   
  77.                 /images/**=anon  
  78.                 /js/**=anon   
  79.                 /upload/**=anon   
  80.                 <!-- /userList=roles[admin] -->  
  81.                 /userList=kickout,authc,perms[/userList]  
  82.                 /toRegister=kickout,authc,perms[/toRegister]  
  83.                 /toDeleteUser=kickout,authc,perms[/toDeleteUser]  
  84.                 /** = kickout,authc  
  85.              </value>    
  86.         </property>    
  87.     </bean>    
  88.     
  89.     <!-- securityManager -->    
  90.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">    
  91.         <property name="realm" ref="myRealm" />    
  92.          <property name="sessionManager" ref="sessionManager"/>  
  93.          <property name="cacheManager" ref="shiroEhcacheManager"/>  
  94.     </bean>    
  95.     <!-- 自定义Realm实现 -->   
  96.     <bean id="myRealm" class="com.core.shiro.CustomRealm" />    
  97.       
  98.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />  
  99.       
  100.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">    
  101.        <property name="prefix" value="/"/>    
  102.        <property name="suffix" value=".jsp"></property>    
  103.     </bean>  
  104. </beans>    

ehcache.xml

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  3.     xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"    
  4.     updateCheck="false" maxBytesLocalDisk="20G" maxBytesLocalOffHeap="50M">  
  5.         
  6.     <diskStore path="java.io.tmpdir"/> <!-- 系统的默认临时文件路径 -->  
  7.     <defaultCache eternal="false"     
  8.         maxElementsInMemory="10000"    
  9.         overflowToDisk="false"     
  10.         timeToIdleSeconds="0"    
  11.         timeToLiveSeconds="0"     
  12.         memoryStoreEvictionPolicy="LFU" />    
  13.    <!--   
  14.     eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。  
  15.     maxElementsInMemory:缓存中允许创建的最大对象数  
  16.     overflowToDisk:内存不足时,是否启用磁盘缓存。  
  17.     timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,  
  18.             两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,  
  19.      如果该值是 0 就意味着元素可以停顿无穷长的时间。  
  20.     timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,  
  21.            这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。  
  22.     memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。  
  23.     1 FIFO,先进先出  
  24.     2 LFU,最少被使用,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。  
  25.     3 LRU,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。  
  26.     -->  
  27.     <cache name="myCache"  eternal="false"     
  28.         maxElementsInMemory="10000"    
  29.         overflowToDisk="false"     
  30.         timeToIdleSeconds="0"    
  31.         timeToLiveSeconds="0"     
  32.         memoryStoreEvictionPolicy="LFU" />    
  33.     <cache name="shiro-activeSessionCache" eternal="false"  
  34.           maxElementsInMemory="10000"    
  35.           overflowToDisk="true"  
  36.           timeToIdleSeconds="0"  
  37.           timeToLiveSeconds="0"/>  
  38. </ehcache>   

login.jsp的javascript:

[javascript] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <script type="text/javascript">  
  2.     function kickout(){  
  3.        var href=location.href;  
  4.        if(href.indexOf("kickout")>0){  
  5.            alert("您的账号在另一台设备上登录,您被挤下线,若不是您本人操作,请立即修改密码!");  
  6.        }   
  7.     }  
  8.     window.onload=kickout();   
  9. </script>  

KickoutSessionControlFilter:

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. package com.core.shiro;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Deque;  
  5. import java.util.LinkedList;  
  6. import javax.servlet.ServletRequest;  
  7. import javax.servlet.ServletResponse;  
  8. import org.apache.shiro.cache.Cache;  
  9. import org.apache.shiro.cache.CacheManager;  
  10. import org.apache.shiro.session.Session;  
  11. import org.apache.shiro.session.mgt.DefaultSessionKey;  
  12. import org.apache.shiro.session.mgt.SessionManager;  
  13. import org.apache.shiro.subject.Subject;  
  14. import org.apache.shiro.web.filter.AccessControlFilter;  
  15. import org.apache.shiro.web.util.WebUtils;  
  16. public class KickoutSessionControlFilter  extends AccessControlFilter{  
  17.     private String kickoutUrl; //踢出后到的地址  
  18.     private boolean kickoutAfter; //踢出之前登录的/之后登录的用户 默认踢出之前登录的用户  
  19.     private int maxSession; //同一个帐号最大会话数 默认1  
  20.     private SessionManager sessionManager;  
  21.     private Cache<String, Deque<Serializable>> cache;  
  22.   
  23.     public void setKickoutUrl(String kickoutUrl) {  
  24.         this.kickoutUrl = kickoutUrl;  
  25.     }  
  26.   
  27.     public void setKickoutAfter(boolean kickoutAfter) {  
  28.         this.kickoutAfter = kickoutAfter;  
  29.     }  
  30.   
  31.     public void setMaxSession(int maxSession) {  
  32.         this.maxSession = maxSession;  
  33.     }  
  34.   
  35.     public void setSessionManager(SessionManager sessionManager) {  
  36.         this.sessionManager = sessionManager;  
  37.     }  
  38.   
  39.     public void setCacheManager(CacheManager cacheManager) {  
  40.         this.cache = cacheManager.getCache("shiro-activeSessionCache");  
  41.     }  
  42.      /** 
  43.       * 是否允许访问,返回true表示允许 
  44.       */  
  45.     @Override  
  46.     protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {  
  47.         return false;  
  48.     }  
  49.     /** 
  50.      * 表示访问拒绝时是否自己处理,如果返回true表示自己不处理且继续拦截器链执行,返回false表示自己已经处理了(比如重定向到另一个页面)。 
  51.      */  
  52.     @Override  
  53.     protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {  
  54.         Subject subject = getSubject(request, response);  
  55.         if(!subject.isAuthenticated() && !subject.isRemembered()) {  
  56.             //如果没有登录,直接进行之后的流程  
  57.             return true;  
  58.         }  
  59.   
  60.         Session session = subject.getSession();  
  61.         String username = (String) subject.getPrincipal();  
  62.         Serializable sessionId = session.getId();  
  63.   
  64.         // 初始化用户的队列放到缓存里  
  65.         Deque<Serializable> deque = cache.get(username);  
  66.         if(deque == null) {  
  67.             deque = new LinkedList<Serializable>();  
  68.             cache.put(username, deque);  
  69.         }  
  70.   
  71.         //如果队列里没有此sessionId,且用户没有被踢出;放入队列  
  72.         if(!deque.contains(sessionId) && session.getAttribute("kickout") == null) {  
  73.             deque.push(sessionId);  
  74.         }  
  75.   
  76.         //如果队列里的sessionId数超出最大会话数,开始踢人  
  77.         while(deque.size() > maxSession) {  
  78.             Serializable kickoutSessionId = null;  
  79.             if(kickoutAfter) { //如果踢出后者  
  80.                 kickoutSessionId=deque.getFirst();  
  81.                 kickoutSessionId = deque.removeFirst();  
  82.             } else { //否则踢出前者  
  83.                 kickoutSessionId = deque.removeLast();  
  84.             }  
  85.             try {  
  86.                 Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));  
  87.                 if(kickoutSession != null) {  
  88.                     //设置会话的kickout属性表示踢出了  
  89.                     kickoutSession.setAttribute("kickout", true);  
  90.                 }  
  91.             } catch (Exception e) {//ignore exception  
  92.                 e.printStackTrace();  
  93.             }  
  94.         }  
  95.   
  96.         //如果被踢出了,直接退出,重定向到踢出后的地址  
  97.         if (session.getAttribute("kickout") != null) {  
  98.             //会话被踢出了  
  99.             try {  
  100.                 subject.logout();  
  101.             } catch (Exception e) {   
  102.             }  
  103.             WebUtils.issueRedirect(request, response, kickoutUrl);  
  104.             return false;  
  105.         }  
  106.         return true;  
  107.     }  
  108. }  

http://blog.csdn.net/qq_33556185/article/details/51744004

原文地址:https://www.cnblogs.com/chen110xi/p/5690867.html