• 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

  • 相关阅读:
    Boost之使用篇(1)
    Lucene 3.0.0细节初窥(1)深入探索Lucene的consumer与processor
    整理一点关于Lucene的学习资料, 方便自己与别人查看
    使用Lucene 3.0.0的结构遍历TokenStream的内容.
    [原创]如何写一个完善的c++异常处理类
    Lucene 3.0.0 的TokenStream与Analyzer
    Lucene 3.0.0 之样例解析(4)IndexFiles.java
    贝叶斯、概率分布与机器学习
    Lucene用c++重写的详细安排
    Lucene 3.0.0的细节初窥(2)研究在索引过程中的缓存
  • 原文地址:https://www.cnblogs.com/hwaggLee/p/7610832.html
Copyright © 2020-2023  润新知