概述

此过滤器用于集成SecurityContextSpring异步执行机制中的WebAsyncManager

源代码解析

package org.spring work.security.web.context.request.async;

import java.io.IOException;
import java.util.concurrent.Callable;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.spring work.security.core.context.SecurityContext;
import org.spring work.web.context.request.async.WebAsyncManager;
import org.spring work.web.context.request.async.WebAsyncUtils;
import org.spring work.web.filter.OncePerRequestFilter;


public final class WebAsyncManagerIntegrationFilter extends OncePerRequestFilter {
	private static final   CALLABLE_INTERCEPTOR_KEY = new  ();

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
       // 从请求属性上获取所绑定的`WebAsyncManager`,如果尚未绑定,先做绑定
       // 相应的属性名称为 : 
       // org.spring work.web.context.request.async.WebAsyncManager.WEB_ASYNC_MANAGER
		WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

       // 从 asyncManager 中获取 key 为 CALLABLE_INTERCEPTOR_KEY 的
       //  SecurityContextCallableProcessingInterceptor,  如果获取到的为 null,
       // 说明其中还没有 key 为 CALLABLE_INTERCEPTOR_KEY 的
      // SecurityContextCallableProcessingInterceptor, 新建一个并使用该 key
      // 注册上去
            
		SecurityContextCallableProcessingInterceptor securityProcessingInterceptor = (SecurityContextCallableProcessingInterceptor) asyncManager
				.getCallableInterceptor(CALLABLE_INTERCEPTOR_KEY);
		if (securityProcessingInterceptor == null) {
        
        // 这里新建的 SecurityContextCallableProcessingInterceptor 实现了
        // 接口 CallableProcessingInterceptor,当它被应用于一次异步执行时,
        // 它的方法beforeConcurrentHandling() 会在调用者线程执行,该方法
        // 会相应地从当前线程获取SecurityContext,然后被调用者线程中执行设计的
        // 逻辑时,会使用这个SecurityContext,从而实现安全上下文从调用者线程
        // 到被调用者线程的传播
			asyncManager.registerCallableInterceptor(CALLABLE_INTERCEPTOR_KEY,
					new SecurityContextCallableProcessingInterceptor());
		}

       // 上面是本过滤器的职责逻辑:为整个请求处理过程中可能的异步处理做安全上下文相关的
       // 准备。现在该任务已经完成,继续 filter chain 的调用。
		filterChain.doFilter(request, response);
	}
}
	

其他文章

Spring Security Web 5.1.2 源码解析 – 安全相关Filter清单

收藏 打印