Apache shiro如何實現一個賬戶同一時刻只有一個人登錄


繼承AuthorizingRealm類,重寫方法doGetAuthenticationInfo

    /**
     * 認證(登錄時調用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        ShiroUser shiroUser = userCache.get(username);
        // 賬號不存在
        if (shiroUser == null) {
            throw new UnknownAccountException("賬號或密碼不正確");
        }
        // 密碼錯誤
        if (!password.equals(shiroUser.getPassword())) {
            throw new IncorrectCredentialsException("賬號或密碼不正確");
        }
        // 賬號鎖定
        if (shiroUser.getStatus() == 0) {
            throw new LockedAccountException("賬號已被鎖定,請聯系管理員");
        }


        //處理session
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        DefaultWebSessionManager sessionManager = (DefaultWebSessionManager)securityManager.getSessionManager();
        Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();//獲取當前已登錄的用戶session列表
        for(Session session:sessions){
            //判斷用是否登錄
            SimplePrincipalCollection simplePrincipalCollection = (SimplePrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if( simplePrincipalCollection != null ){
                ShiroUser user = (ShiroUser)simplePrincipalCollection.getPrimaryPrincipal();
                if(user!= null && username.equals(user.getUsername())) {
                    //session超時
                    if((new Date().getTime()- session.getStartTimestamp().getTime())>= session.getTimeout()){
                        sessionManager.getSessionDAO().delete(session);//移除(提出用戶)
                    }else{
                        //sessionManager.getSessionDAO().delete(session);//移除(提出用戶)
                        throw new LockedAccountException("賬號已在其他處登錄");//不移除(不允許其他人登錄相同用戶)
                    }
                }
            }
        }
 
         

 





        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(shiroUser, password, getName());
        return info;
    }

 以上是臨時解決方案,后面有更好的在補上

 

 

靈感來源:http://www.cnblogs.com/lingxue3769/p/5809543.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM