SecurityContextPersistenceFilter是如何做到任何对 SecurityContext 的改变都可以被 copy 到 HttpSession。

首先查看其中的doFilter方法的代码

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        .......
        //省略部分代码
        HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
        //获取SecurityContext,其中是从httpsession中获取,如果httpsession中没有,则新建并返回一个新的
       SecurityContext contextBeforeChainExecution = repo.loadContext(holder);

        try {
            //将返回的securityContext保存到本地线程中,方便将来访问
           SecurityContextHolder.setContext(contextBeforeChainExecution);

            chain.doFilter(holder.getRequest(), holder.getResponse());

        } finally {
            //获取之前保存的securityContext
            SecurityContext contextAfterChainExecution = SecurityContextHolder.getContext();
            // Crucial removal of SecurityContextHolder contents - do this before anything else.
            //清空SecurityContextHolder中的Context            
            SecurityContextHolder.clearContext();
            //将Security保存到HttpSession中,下次请求的时候就可以利用保存好的SecurityContext
           repo.saveContext(contextAfterChainExecution, holder.getRequest(), holder.getResponse());
            request.removeAttribute(FILTER_APPLIED);

            if (debug) {
                logger.debug("SecurityContextHolder now cleared, as request processing completed");
            }
        }
    }

让我们来看一下loadContext方法

    public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
        HttpServletRequest request = requestResponseHolder.getRequest();
        HttpServletResponse response = requestResponseHolder.getResponse();
        HttpSession httpSession = request.getSession(false);
        //从这就可以看出来,SecurityContext的获取就是从Httpsession中获得的,所以根据java的传址特性,就可以判断出Httpsession会同步SecurityContext的变化
        SecurityContext context = readSecurityContextFromSession(httpSession);

        if (context == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("No SecurityContext was available from the HttpSession: " + httpSession +". " +
                        "A new one will be created.");
            }
            //如果当然session中没有SecurityContext,则重新创建一个新的Context 
           context = generateNewContext();

        }

        requestResponseHolder.setResponse(
                new SaveToSessionResponseWrapper(response, request, httpSession != null, context));

        return context;
    }


你可能感兴趣的:(spring-security)