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

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

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

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

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

shiro.xml

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

ehcache.xml

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

login.jsp的javascript:

  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:

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

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

最新文章

  1. 高性能javascript学习笔记系列(5) -快速响应的用户界面和编程实践
  2. Android activity跳转方式
  3. try throw catch
  4. textViewDidChange: crashes in iOS 7
  5. 状压DP POJ 3254 Corn Fields
  6. S2 第二章数据库的实现
  7. java 面向对象编程 第20章 XML技术解析
  8. 《JavaScript高级程序设计》第4章 变量、作用域和内存问题
  9. Apache服务器配置默认首页文件名和网站路径
  10. Android模拟器报&quot;Failed To Allocate memory 8&quot;错误的解决办法
  11. hdu 4622 Reincarnation(后缀数组)
  12. TFS发布计划发送到钉钉消息群
  13. JAVAscript学习笔记 jsBOM 第七节 (原创) 参考js使用表
  14. iOS js oc相互调用JavaScriptCore(一)
  15. UI Automator 常用 API 整理
  16. 禅道docker化(Centos7.2)
  17. python 爬虫&amp;爬取豆瓣电影top250
  18. linux下启动多个php,分别监听不同的端口。
  19. SpringBoot 配置文件存放位置及读取顺序
  20. 如何把你的eclipse编辑器修改成黑色的主题

热门文章

  1. JavaScript中数组的各种操作方法
  2. 不用call和apply方法模拟实现ES5的bind方法
  3. hashmap实现原理2
  4. Android开发利用Volley框架下载和缓存网络图片
  5. 用 Redis 实现分布式锁(分析)
  6. 海思hi3518 opencv测试
  7. TensorFlow 入门 上(自用)
  8. 转:Mac OS X下Sublime Text (V2.0.1)破解
  9. k-means聚类算法C++实现
  10. DataColumn