apache shiro踢出用戶和獲取所有在線用戶

apache shiro踢出用戶:

產品要求用戶只能在同一個地方登錄,如果之前在其他機器或者瀏覽器上登錄,講之前登錄帳號踢出。applicationContext-shiro.xml配置:

在默認的shiro配置上增加如下配置(本文假設你已經使用過apache shiro,並且已經使用shiro成功實現登錄功能):


<bea id="sessionDAO" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO"/>

<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">

<property name="sessionDAO" ref="sessionDAO"/>

</bean>

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">

<property name="realm" ref="shiroDbRealm" />

<property name="cacheManager" ref="shiroCacheManager" />

<property name="sessionManager" ref="sessionManager" />

</bean>


然後在ShiroDbRealm中的認證方法中增加如下代碼,代碼主要目的就是根據當前登錄名獲取之前使用同樣登錄名登錄後的session

@Autowired

private SessionDAO sessionDAO;

...

String loginName=token.getUsername();

Session currentSession = null;

Collection<Session> sessions = sessionDAO.getActiveSessions();

for(Session session:sessions){

if(loginName.equals(String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY))) {

session.setTimeout(0);//設置session立即失效,即將其踢出系統

break;

}

}

apache shiro獲取所有在線用戶:


Collection<Session> sessions = sessionDAO.getActiveSessions();

for(Session session:sessions){

System.out.println("登錄ip:"+session.getHost());

System.out.println("登錄用戶"+session.getAttribute(DefaultWebContext.PRINCIPALS_SESSION_KEY));

System.out.println("最後操作日期:"+session.getLastAccessTime());

}

紅色部分:MemorySessionDAO ,切記不能使用EnterpriseCacheSessionDAO,使用該類的時候,雖然也能起到踢出用戶的作用,但是後登錄的用戶隔兩三分鐘就會session自動失效。


點擊去我的個人站點查看原文


更多文章,歡迎關注俺的微信訂閱號,每天一篇小筆記,每天提高一點點:

公衆號:enilu123


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