shiro session互踢,一个用户只能一处登录

shiro 实现redis共享session, 一个用户只能一处登录

shiro 核心类AuthorizingRealm, 自己写一个类AuthRealm继承AuthorizingRealm

@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("doGetAuthenticationInfo------------------登录------------------");
        UsernamePasswordToken utoken = (UsernamePasswordToken) token;
        String userName = utoken.getUsername();
        // Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
        SystemUser systemUser = jwUserService.selectByUserName(userName);
        if(systemUser == null){
            throw new UnknownAccountException();
        }
        /** 店铺切换到XX才能登陆 */
        if(!String.valueOf(PlatformEnum.PLATFORM_8.getCode()).equals(String.valueOf(systemUser.getSlw().getSvip()))){
            throw new NotCurrentSystemException("请您切换成当前系统再来登陆吧!");
        }
        /** 删除状态 */
        if(SystemUser.STATUS_DELETE.equals(systemUser.getStatus())){
            throw new LockedAccountException();
        }
        /**账号无任何权限*/
        Set roles = systemUser.getRoles();
        if(roles != null && !roles.isEmpty()){
            Set menus = roles.iterator().next().getMenus();
            if(menus == null || menus.isEmpty()){
                throw new NonePermissionException("您的账号无任何权限!");
            }
        }
        //放入shiro.调用CredentialsMatcher检验密码
        SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(systemUser, systemUser.getPassword(), this.getClass().getName());
        Session session = SecurityUtils.getSubject().getSession();
        String sessionId = session.getId().toString();
        Long userId = systemUser.getUserid();
        /** session共享,账号互踢 */
        String singleSessionId = redisManager.hGetV(RedisSessionDao.SHIRO_SINGLE_KEY, userId);
        if (StringUtils.isNotBlank(singleSessionId) && !sessionId.equals(singleSessionId)) {
            log.info(" session old : " + singleSessionId + " , session new : " + sessionId);
            redisManager.hdelete(RedisSessionDao.SESSION_KEY, singleSessionId);
        }
        redisManager.hSetV(RedisSessionDao.SHIRO_SINGLE_KEY, userId, sessionId);
        return sai;
    }

PS:此处只写了相关有用代码,无关代码没有贴

你可能感兴趣的:(技术,shiro,SpringBoot)