Apache shiro如何實現一個帳戶同一時刻只有一我的登陸

繼承AuthorizingRealm類,重寫方法doGetAuthenticationInfohtml

    /**
     * 認證(登陸時調用)
     */
    @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;
    }

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

 

 

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

相關文章
相關標籤/搜索