為了安全起見,同一個賬號理應同時只能在一台設備上登錄,后面登錄的踢出前面登錄的。用Shiro可以輕松實現此功能。
shiro中sessionManager是專門作會話管理的,而sessinManager將會話保存在sessionDAO中,如果不給sessionManager注入
sessionDAO,會話將是瞬時狀態,沒有被保存起來,從sessionManager里取session,是取不到的。
此例中sessionDAO注入了Ehcache緩存,會話被保存在Ehcache中,不知Ehcache為何物的,請自行查閱資料。
完整demo下載:http://download.csdn.net/detail/qq_33556185/9555720
shiro.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <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"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.2.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
- <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
- <property name="globalSessionTimeout" value="1800000"/>
- <property name="deleteInvalidSessions" value="true"/>
- <property name="sessionDAO" ref="sessionDAO"/>
- <property name="sessionIdCookieEnabled" value="true"/>
- <property name="sessionIdCookie" ref="sessionIdCookie"/>
- <property name="sessionValidationSchedulerEnabled" value="true"/>
- <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
- <property name="cacheManager" ref="shiroEhcacheManager"/>
- </bean>
- <!-- 會話DAO,sessionManager里面的session需要保存在會話Dao里,沒有會話Dao,session是瞬時的,沒法從
- sessionManager里面拿到session -->
- <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
- <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
- <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
- </bean>
- <!-- 緩存管理器 -->
- <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
- <property name="cacheManagerConfigFile" value="classpath:ehcache.xml" />
- </bean>
- <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
- <constructor-arg value="sid"/>
- <property name="httpOnly" value="true"/>
- <property name="maxAge" value="-1"/>
- </bean>
- <!-- 會話ID生成器 -->
- <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"></bean>
- <bean id="kickoutSessionControlFilter" class="com.core.shiro.KickoutSessionControlFilter">
- <property name="sessionManager" ref="sessionManager"/>
- <property name="cacheManager" ref="shiroEhcacheManager"/>
- <property name="kickoutAfter" value="false"/>
- <property name="maxSession" value="1"/>
- <property name="kickoutUrl" value="/toLogin?kickout=1"/>
- </bean>
- <bean id="logout" class="org.apache.shiro.web.filter.authc.LogoutFilter">
- <property name="redirectUrl" value="/toLogin" />
- </bean>
- <!-- 會話驗證調度器 -->
- <bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler ">
- <property name="interval" value="1800000"/>
- <property name="sessionManager" ref="sessionManager"/>
- </bean>
- <!-- Shiro Filter 攔截器相關配置 -->
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
- <!-- securityManager -->
- <property name="securityManager" ref="securityManager" />
- <!-- 登錄路徑 -->
- <property name="loginUrl" value="/toLogin" />
- <!-- 用戶訪問無權限的鏈接時跳轉此頁面 -->
- <property name="unauthorizedUrl" value="/unauthorizedUrl.jsp" />
- <!-- 過濾鏈定義 -->
- <property name="filters">
- <map>
- <entry key="kickout" value-ref="kickoutSessionControlFilter"/>
- </map>
- </property>
- <property name="filterChainDefinitions">
- <value>
- /loginin=kickout,anon
- /logout = logout
- /toLogin=anon
- /css/**=anon
- /html/**=anon
- /images/**=anon
- /js/**=anon
- /upload/**=anon
- <!-- /userList=roles[admin] -->
- /userList=kickout,authc,perms[/userList]
- /toRegister=kickout,authc,perms[/toRegister]
- /toDeleteUser=kickout,authc,perms[/toDeleteUser]
- /** = kickout,authc
- </value>
- </property>
- </bean>
- <!-- securityManager -->
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <property name="realm" ref="myRealm" />
- <property name="sessionManager" ref="sessionManager"/>
- <property name="cacheManager" ref="shiroEhcacheManager"/>
- </bean>
- <!-- 自定義Realm實現 -->
- <bean id="myRealm" class="com.core.shiro.CustomRealm" />
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/"/>
- <property name="suffix" value=".jsp"></property>
- </bean>
- </beans>
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" maxBytesLocalDisk="20G" maxBytesLocalOffHeap="50M">
- <diskStore path="java.io.tmpdir"/> <!-- 系統的默認臨時文件路徑 -->
- <defaultCache eternal="false"
- maxElementsInMemory="10000"
- overflowToDisk="false"
- timeToIdleSeconds="0"
- timeToLiveSeconds="0"
- memoryStoreEvictionPolicy="LFU" />
- <!--
- eternal:緩存中對象是否為永久的,如果是,超時設置將被忽略,對象從不過期。
- maxElementsInMemory:緩存中允許創建的最大對象數
- overflowToDisk:內存不足時,是否啟用磁盤緩存。
- timeToIdleSeconds:緩存數據的鈍化時間,也就是在一個元素消亡之前,
- 兩次訪問時間的最大時間間隔值,這只能在元素不是永久駐留時有效,
- 如果該值是 0 就意味着元素可以停頓無窮長的時間。
- timeToLiveSeconds:緩存數據的生存時間,也就是一個元素從構建到消亡的最大時間間隔值,
- 這只能在元素不是永久駐留時有效,如果該值是0就意味着元素可以停頓無窮長的時間。
- memoryStoreEvictionPolicy:緩存滿了之后的淘汰算法。
- 1 FIFO,先進先出
- 2 LFU,最少被使用,緩存的元素有一個hit屬性,hit值最小的將會被清出緩存。
- 3 LRU,最近最少使用的,緩存的元素有一個時間戳,當緩存容量滿了,而又需要騰出地方來緩存新的元素的時候,那么現有緩存元素中時間戳離當前時間最遠的元素將被清出緩存。
- -->
- <cache name="myCache" eternal="false"
- maxElementsInMemory="10000"
- overflowToDisk="false"
- timeToIdleSeconds="0"
- timeToLiveSeconds="0"
- memoryStoreEvictionPolicy="LFU" />
- <cache name="shiro-activeSessionCache" eternal="false"
- maxElementsInMemory="10000"
- overflowToDisk="true"
- timeToIdleSeconds="0"
- timeToLiveSeconds="0"/>
- </ehcache>
login.jsp的javascript:
- <script type="text/javascript">
- function kickout(){
- var href=location.href;
- if(href.indexOf("kickout")>0){
- alert("您的賬號在另一台設備上登錄,您被擠下線,若不是您本人操作,請立即修改密碼!");
- }
- }
- window.onload=kickout();
- </script>
KickoutSessionControlFilter:
- package com.core.shiro;
- import java.io.Serializable;
- import java.util.Deque;
- import java.util.LinkedList;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import org.apache.shiro.cache.Cache;
- import org.apache.shiro.cache.CacheManager;
- import org.apache.shiro.session.Session;
- import org.apache.shiro.session.mgt.DefaultSessionKey;
- import org.apache.shiro.session.mgt.SessionManager;
- import org.apache.shiro.subject.Subject;
- import org.apache.shiro.web.filter.AccessControlFilter;
- import org.apache.shiro.web.util.WebUtils;
- public class KickoutSessionControlFilter extends AccessControlFilter{
- private String kickoutUrl; //踢出后到的地址
- private boolean kickoutAfter; //踢出之前登錄的/之后登錄的用戶 默認踢出之前登錄的用戶
- private int maxSession; //同一個帳號最大會話數 默認1
- private SessionManager sessionManager;
- private Cache<String, Deque<Serializable>> cache;
- public void setKickoutUrl(String kickoutUrl) {
- this.kickoutUrl = kickoutUrl;
- }
- public void setKickoutAfter(boolean kickoutAfter) {
- this.kickoutAfter = kickoutAfter;
- }
- public void setMaxSession(int maxSession) {
- this.maxSession = maxSession;
- }
- public void setSessionManager(SessionManager sessionManager) {
- this.sessionManager = sessionManager;
- }
- public void setCacheManager(CacheManager cacheManager) {
- this.cache = cacheManager.getCache("shiro-activeSessionCache");
- }
- /**
- * 是否允許訪問,返回true表示允許
- */
- @Override
- protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
- return false;
- }
- /**
- * 表示訪問拒絕時是否自己處理,如果返回true表示自己不處理且繼續攔截器鏈執行,返回false表示自己已經處理了(比如重定向到另一個頁面)。
- */
- @Override
- protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
- Subject subject = getSubject(request, response);
- if(!subject.isAuthenticated() && !subject.isRemembered()) {
- //如果沒有登錄,直接進行之后的流程
- return true;
- }
- Session session = subject.getSession();
- String username = (String) subject.getPrincipal();
- Serializable sessionId = session.getId();
- // 初始化用戶的隊列放到緩存里
- Deque<Serializable> deque = cache.get(username);
- if(deque == null) {
- deque = new LinkedList<Serializable>();
- cache.put(username, deque);
- }
- //如果隊列里沒有此sessionId,且用戶沒有被踢出;放入隊列
- if(!deque.contains(sessionId) && session.getAttribute("kickout") == null) {
- deque.push(sessionId);
- }
- //如果隊列里的sessionId數超出最大會話數,開始踢人
- while(deque.size() > maxSession) {
- Serializable kickoutSessionId = null;
- if(kickoutAfter) { //如果踢出后者
- kickoutSessionId=deque.getFirst();
- kickoutSessionId = deque.removeFirst();
- } else { //否則踢出前者
- kickoutSessionId = deque.removeLast();
- }
- try {
- Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
- if(kickoutSession != null) {
- //設置會話的kickout屬性表示踢出了
- kickoutSession.setAttribute("kickout", true);
- }
- } catch (Exception e) {//ignore exception
- e.printStackTrace();
- }
- }
- //如果被踢出了,直接退出,重定向到踢出后的地址
- if (session.getAttribute("kickout") != null) {
- //會話被踢出了
- try {
- subject.logout();
- } catch (Exception e) {
- }
- WebUtils.issueRedirect(request, response, kickoutUrl);
- return false;
- }
- return true;
- }
- }
http://blog.csdn.net/qq_33556185/article/details/51744004