欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

shiro同一用户后登陆踢出前面的用户

程序员文章站 2022-07-14 19:58:31
...

直接上代码
下面就是我实现的访问控制拦截器:KickoutSessionControlFilter:

public class KickoutSessionControlFilter extends AccessControlFilter {
	
	private static Logger logger = LoggerFactory.getLogger(KickoutSessionControlFilter.class);

    private String kickoutUrl; //踢出后到的地址
    private boolean kickoutAfter = false; //踢出之前登录的/之后登录的用户 默认踢出之前登录的用户
    private int maxSession = 1; //同一个帐号最大会话数 默认1

    private SessionManager sessionManager;
    private Cache<String, Deque<Serializable>> cache;

    public void setKickoutUrl(String kickoutUrl) {
        this.kickoutUrl = kickoutUrl;
    }

    public void setKickoutAfter(boolean kickoutAfter) {
        this.kickoutAfter = kickoutAfter;
    }

    public void setMaxSession(int maxSession) {
        this.maxSession = maxSession;
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    public void setCacheManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache("shiro-kickout-session");
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        if(!subject.isAuthenticated() && !subject.isRemembered()) {
            //如果没有登录,直接进行之后的流程
            return true;
        }

        Session session = subject.getSession();
        ShiroUser user = (ShiroUser) subject.getPrincipal();
        String username = user.getUserName();
        Serializable sessionId = session.getId();

        //读取缓存   没有就存入
        Deque<Serializable> deque = cache.get(username);
        if(deque == null) {
            deque = new LinkedList<Serializable>();
            cache.put(username, deque);
        }

        //如果队列里没有此sessionId,且用户没有被踢出;放入队列
        if(!deque.contains(sessionId) && session.getAttribute("kickout") == null) {
            deque.push(sessionId);
        }

        //如果队列里的sessionId数超出最大会话数,开始踢人
        while(deque.size() > maxSession) {
            Serializable kickoutSessionId = null;
            if(kickoutAfter) { //如果踢出后者
                kickoutSessionId = deque.removeFirst();
            } else { //否则踢出前者
                kickoutSessionId = deque.removeLast();
            }
            try {
                Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
                if(kickoutSession != null) {
                    //设置会话的kickout属性表示踢出了
                    kickoutSession.setAttribute("kickout", true);
                }
            } catch (Exception e) {//ignore exception
            	e.printStackTrace();
            }
        }

        //如果被踢出了,直接退出,重定向到踢出后的地址
        if (session.getAttribute("kickout") != null) {
            //会话被踢出了
            try {
                subject.logout();
            } catch (Exception e) { //ignore
            }
            saveRequest(request);
            
            HttpServletRequest httpRequest = WebUtils.toHttp(request);
            if (com.frame.utils.WebUtils.isAjax(httpRequest)) {
            	logger.debug("当前用户已经在其他地方登录,并且是Ajax请求!");
                HttpServletResponse httpServletResponse = WebUtils.toHttp(response);  
                // 向http头添加 状态 sessionstatus
                httpServletResponse.setHeader("sessionstatus", "kickout");
                // 向http头添加登录的url
                httpServletResponse.addHeader("loginPath", kickoutUrl);
//                httpServletResponse.sendError(ShiroFilterUtils.HTTP_STATUS_SESSION_EXPIRE);
                return false;
            } else {
            	request.setAttribute("user_status", "300");
            	request.setAttribute("message", "您已经在其他地方登录,请重新登录!");
            	request.getRequestDispatcher(kickoutUrl).forward(request, response);
                return false;
            }
        }

        return true;
    }
    
}

如果是springMVC+shiro就将这个自定义的拦截器配置在shiro.xml文件中:

<bean id="kickoutSessionControlFilter" class="com.platform.shiro.KickoutSessionControlFilter">
		<property name="cacheManager" ref="shiroEhcacheManager" />
		<property name="sessionManager" ref="sessionManager" />
		<!-- 是否踢出后来登录的,默认是false;即后者登录的用户踢出前者登录的用户 -->
		<property name="kickoutAfter" value="false" />
		<!-- 同一个用户最大的会话数,默认1;比如2的意思是同一个用户允许最多同时两个人登录 -->
		<property name="maxSession" value="1" />
		<property name="kickoutUrl" value="/login" />
</bean>

是springboot+shiro拦截器配置在ShiroConfig.java文件中:

/**
  * 限制同一账号登录同时登录人数控制
  * @return
  */
 public KickoutSessionControlFilter kickoutSessionControlFilter(){
    KickoutSessionControlFilter kickoutSessionControlFilter = new KickoutSessionControlFilter();
    //使用cacheManager获取相应的cache来缓存用户登录的会话;用于保存用户—会话之间的关系的;
    //这里我们还是用之前shiro使用的redisManager()实现的cacheManager()缓存管理
    //也可以重新另写一个,重新配置缓存时间之类的自定义缓存属性
    kickoutSessionControlFilter.setCacheManager(cacheManager());
    //用于根据会话ID,获取会话进行踢出操作的;
    kickoutSessionControlFilter.setSessionManager(sessionManager());
    //是否踢出后来登录的,默认是false;即后者登录的用户踢出前者登录的用户;踢出顺序。
    kickoutSessionControlFilter.setKickoutAfter(false);
    //同一个用户最大的会话数,默认1;比如2的意思是同一个用户允许最多同时两个人登录;
    kickoutSessionControlFilter.setMaxSession(1);
    //被踢出后重定向到的地址;
    kickoutSessionControlFilter.setKickoutUrl("/kickout");
     return kickoutSessionControlFilter;
  }

在将这个kickoutSessionControlFilter()注入到shiroFilterFactoryBean中:

//自定义拦截器
Map<String, Filter> filtersMap = new LinkedHashMap<String, Filter>();
//限制同一帐号同时在线的个数。
filtersMap.put("kickout", kickoutSessionControlFilter());
shiroFilterFactoryBean.setFilters(filtersMap);
相关标签: 管理在线用户