SpringSecurity-ConcurrentSessionFilter的作用

  ConcurrentSessionFilter主要有两个功能:

    (1)每次request时调用SessionRegistry的refreshLastRequest(String)更新session的最后更新时间

    (2)每次request时从SessionRegistry中获取SessionInformation,并且判断session是否已失效,如果失效就调用LogoutFilter并注销session(session的认证信息也一起销毁)。这里有sessioin的一些限制逻辑要考虑,如只运行用户只能在一个地方登陆等,我暂时没使用这一块,所以先不深究。

这个Filter逻辑还比较简单,功能也比较明确,下面直接贴核心代码

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        HttpSession session = request.getSession(false);

        if (session != null) {
            SessionInformation info = sessionRegistry.getSessionInformation(session
                    .getId());

            if (info != null) {
                if (info.isExpired()) {
                    // Expired - abort processing
                    doLogout(request, response);

                    String targetUrl = determineExpiredUrl(request, info);

                    if (targetUrl != null) {
                        redirectStrategy.sendRedirect(request, response, targetUrl);

                        return;
                    }
                    else {
                        response.getWriter().print(
                                "This session has been expired (possibly due to multiple concurrent "
                                        + "logins being attempted as the same user).");
                        response.flushBuffer();
                    }

                    return;
                }
                else {
                    // Non-expired - update last request date/time
                    sessionRegistry.refreshLastRequest(info.getSessionId());
                }
            }
        }

        chain.doFilter(request, response);
    }
原文地址:https://www.cnblogs.com/zsxneil/p/6622129.html