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

相关文章
相关标签/搜索