继承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