zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    文件操作2
    操作文件1
    标准库(一):collections之orderedDict
    类的模板导入
    类的继承
    类内成员和方法的使用
    redis高可用
    oracle数据库优化
    如何捕获oracle数据库异常
    oracle之语句触发器创建
  • 原文地址:https://www.cnblogs.com/hwaggLee/p/7610832.html
Copyright © 2011-2022 走看看