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;
    }


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值