2.过滤器链加载原理

简介: 本文深入解析Spring Security底层过滤机制,揭秘十五个过滤器如何通过DelegatingFilterProxy、FilterChainProxy和SecurityFilterChain自动加载与执行,帮助理解框架背后的工作原理。

通过前面十五个过滤器功能的介绍,对于SpringSecurity简单入门中的疑惑是不是在心中已经有了答案了呀? 但新的问题来了!我们并没有配置这些过滤器啊?它们都是怎么被加载出来的?

1-DelegatingFilterProxy

我们在web.xml中配置了一个名称为springSecurityFilterChain的过滤器DelegatingFilterProxy,接下我直接对 DelegatingFilterProxy源码里重要代码进行说明,其中删减掉了一些不重要的代码,大家注意我写的注释就行了!

public class DelegatingFilterProxy extends GenericFilterBean {
    @Nullable 
    private String contextAttribute; 
    @Nullable 
    private WebApplicationContext webApplicationContext; 
    @Nullable 
    private String targetBeanName; 
    private boolean targetFilterLifecycle; 
    @Nullable 
    private volatile Filter delegate;//注:这个过滤器才是真正加载的过滤器 
    private final Object delegateMonitor; 
    //注:doFilter才是过滤器的入口,直接从这看! 
    public void doFilter(ServletRequest request, 
                         ServletResponse response, 
                         FilterChain 
                         filterChain) throws ServletException, IOException { 
        Filter delegateToUse = this.delegate; 
        if (delegateToUse == null) { 
            synchronized(this.delegateMonitor) { 
                delegateToUse = this.delegate; 
                if (delegateToUse == null) { 
                    WebApplicationContext wac = this.findWebApplicationContext(); 
                    if (wac == null) { 
                        throw new IllegalStateException("No WebApplicationContext found: no 
                        ContextLoaderListener or DispatcherServlet registered?"); 
                    } 
                    //第一步:doFilter中最重要的一步,初始化上面私有过滤器属性delegate 
                    delegateToUse = this.initDelegate(wac); 
                } 
                this.delegate = delegateToUse; 
            } 
        } 
        //第三步:执行FilterChainProxy过滤器 
        this.invokeDelegate(delegateToUse, request, response, filterChain); 
    } 
    //第二步:直接看最终加载的过滤器到底是谁 
    protected Filter initDelegate(WebApplicationContext wac) throws ServletException { 
        //debug得知targetBeanName为:springSecurityFilterChain 
        String targetBeanName = this.getTargetBeanName(); 
        Assert.state(targetBeanName != null, "No target bean name set"); 
        //debug得知delegate对象为:FilterChainProxy 
        Filter delegate = (Filter)wac.getBean(targetBeanName, Filter.class); 
        if (this.isTargetFilterLifecycle()) { 
            delegate.init(this.getFilterConfig()); 
      } 
    return delegate; 
    }
}

第二步debug结果如下:

由此可知,DelegatingFilterProxy通过springSecurityFilterChain这个名称,得到了一个FilterChainProxy过滤器, 最终在第三步执行了这个过滤器。

2-FilterChainProxy

注意代码注释!

public class FilterChainProxy extends GenericFilterBean {
    private static final Log logger = LogFactory.getLog(FilterChainProxy.class);
    private static final String FILTER_APPLIED =
    FilterChainProxy.class.getName().concat(".APPLIED");
    private List<SecurityFilterChain> filterChains;
    private FilterChainProxy.FilterChainValidator filterChainValidator;
    private HttpFirewall firewall;
    //咿!?可以通过一个叫SecurityFilterChain的对象实例化出一个FilterChainProxy对象
    //这FilterChainProxy又是何方神圣?会不会是真正的过滤器链对象呢?先留着这个疑问!
    public FilterChainProxy(SecurityFilterChain chain) {
        this(Arrays.asList(chain));
    }
    //又是SecurityFilterChain这家伙!嫌疑更大了!
    public FilterChainProxy(List<SecurityFilterChain> filterChains) {
        this.filterChainValidator = new FilterChainProxy.NullFilterChainValidator();
        this.firewall = new StrictHttpFirewall();
        this.filterChains = filterChains;
    }
    //注:直接从doFilter看
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
        boolean clearContext = request.getAttribute(FILTER_APPLIED) == null;
        if (clearContext) {
            try {
                request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
                this.doFilterInternal(request, response, chain);
            } finally {
                SecurityContextHolder.clearContext();
                request.removeAttribute(FILTER_APPLIED);
            }
        } else {
            //第一步:具体操作调用下面的doFilterInternal方法了
            this.doFilterInternal(request, response, chain);
        }
    }
    private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain
                                  chain) throws IOException, ServletException {
        FirewalledRequest fwRequest =
        this.firewall.getFirewalledRequest((HttpServletRequest)request);
        HttpServletResponse fwResponse =
        this.firewall.getFirewalledResponse((HttpServletResponse)response);
        //第二步:封装要执行的过滤器链,那么多过滤器就在这里被封装进去了!
        List<Filter> filters = this.getFilters((HttpServletRequest)fwRequest);
        if (filters != null && filters.size() != 0) {
            FilterChainProxy.VirtualFilterChain vfc = new
            FilterChainProxy.VirtualFilterChain(fwRequest, chain, filters);
            //第四步:加载过滤器链
            vfc.doFilter(fwRequest, fwResponse);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug(UrlUtils.buildRequestUrl(fwRequest) 
                             + (filters == null ? " has no matching filters" : " has an empty filter list"));
            }
            fwRequest.reset();
            chain.doFilter(fwRequest, fwResponse);
        }
    }
    private List<Filter> getFilters(HttpServletRequest request) {
        Iterator var2 = this.filterChains.iterator();
        //第三步:封装过滤器链到SecurityFilterChain中!
        SecurityFilterChain chain;
        do {
            if (!var2.hasNext()) {
                return null;
            }
                chain = (SecurityFilterChain)var2.next();
    } while(!chain.matches(request));
    return chain.getFilters();
  }
}

第二步debug结果如下图所示,惊不惊喜?十五个过滤器都在这里了!

再看第三步,怀疑这么久!原来这些过滤器还真是都被封装进SecurityFilterChain中了。

3-SecurityFilterChain

最后看SecurityFilterChain,这是个接口,实现类也只有一个,这才是web.xml中配置的过滤器链对象!

//接口
public interface SecurityFilterChain {
    boolean matches(HttpServletRequest var1);
    List<Filter> getFilters();
}
//实现类
public final class DefaultSecurityFilterChain implements SecurityFilterChain {
    
    private static final Log logger = LogFactory.getLog(DefaultSecurityFilterChain.class);
    private final RequestMatcher requestMatcher;
    private final List<Filter> filters;
    
    public DefaultSecurityFilterChain(RequestMatcher requestMatcher,
                                      Filter... filters) {
        this(requestMatcher, Arrays.asList(filters));
    }
    
    public DefaultSecurityFilterChain(RequestMatcher requestMatcher, 
                                      List<Filter> filters) {
        logger.info("Creating filter chain: " + requestMatcher + ", " + filters);
        this.requestMatcher = requestMatcher;
        this.filters = new ArrayList(filters);
    }
    
    public RequestMatcher getRequestMatcher() {
        return this.requestMatcher;
    }
    
    public List<Filter> getFilters() {
        return this.filters;
    }
    
    public boolean matches(HttpServletRequest request) {
        return this.requestMatcher.matches(request);
    }
    
    public String toString() {
        return "[ " + this.requestMatcher + ", " + this.filters + "]";
    }
}

总结:通过此章节,我们对SpringSecurity工作原理有了一定的认识。但理论千万条,功能第一条,探寻底层,是为了更好的使用框架。 那么,言归正传!到底如何使用自己的页面来实现SpringSecurity的认证操作呢?要完成此功能,首先要有一套自己的页面!

相关文章
|
11月前
|
持续交付
阿里巴巴-云效
本文介绍了如何开通云效服务并进行需求与代码管理。首先访问官网开通服务,随后在需求管理中创建项目、邀请成员并跟踪任务,支持看板模式以便直观管理。接着了解代码托管平台的使用,包括创建代码库、初始化工程、提交代码及构建自动化流水线,实现代码的自动部署与发布,重点在于流程体验。
|
11月前
|
存储 JSON NoSQL
3-MongoDB常用命令
本文介绍MongoDB数据库操作,包括创建与删除数据库、集合的显式与隐式创建、文档的增删改查、批量操作、分页查询及排序统计等基本CRUD操作,适用于文章评论数据管理。
|
11月前
|
存储 缓存 运维
一场FullGC故障排查
本文记录了一次Java应用CPU使用率异常升至104%的排查过程。通过分析发现,问题由Full GC频繁触发导致,根源在于将大体积Excel数据以List&lt;Map&lt;String, String&gt;&gt;形式加载至JVM内存,造成堆内存膨胀且长期驻留,最终引发内存压力和GC风暴。结合JProfiler工具定位到大对象后,提出“治本”(移出JVM内存)与“治标”(精简数据结构)两类解决方案,并总结了从监控识别、工具分析到代码优化的完整排查思路,强调应关注JVM层面而非仅机器指标。
|
11月前
|
监控 算法 Unix
Thread.sleep(0) 到底有什么用(读完就懂)
本文深入解析Thread.Sleep函数的工作原理,结合操作系统调度机制,揭示Sleep(1000)未必准时唤醒、Sleep(0)却能触发CPU重新竞争的真相,帮助开发者正确理解线程挂起与CPU调度的关系。
|
11月前
|
运维 Devops 开发工具
生产环境缺陷管理
git-poison基于go-git实现分布式bug追溯,解决多分支开发中bug漏修、漏发等协同难题,自动化卡点发布流程,降低沟通成本,提升发布安全性与效率。
生产环境缺陷管理
|
11月前
|
Java Linux 开发工具
Linux
本文介绍如何将一个SpringBoot应用打包并部署到Linux服务器。包括项目搭建、JAR包打包、JDK安装配置、应用上传与启动,以及通过心跳接口验证服务是否正常运行的完整流程,适用于Java应用的Linux部署入门学习。
Linux
|
11月前
|
Java 测试技术 Linux
生产环境发布管理
本文介绍大型团队中基于自动化部署平台(CI/CD)的多环境发布流程,涵盖dev、test、pre、prod各环境职责,以及如何通过Jenkins+K8S实现高效部署与回滚,并结合Skywalking等工具进行日志追踪与问题排查。
生产环境发布管理
|
11月前
|
前端开发 程序员
常见注解及使用说明
本文介绍SpringMVC中@RequestMapping注解的作用及原理,讲解如何通过注解将HTTP请求映射到控制器方法,并列举@GetMapping等派生注解,帮助理解前后端接口的对应关系。
|
11月前
|
测试技术 UED
发布模式
蓝绿部署通过两套系统(蓝/绿)并行,实现零停机发布与快速回滚;金丝雀发布逐步替换旧版本,降低风险;A/B测试则用于对比多版本效果,优化用户体验。三者适用场景不同,各有侧重。
发布模式
|
11月前
|
存储 安全 前端开发
1.认识OAuth2.0
OAuth2.0是一种开放授权标准,允许第三方应用在用户授权下安全访问资源,无需获取用户账号密码。其核心是通过令牌(token)实现有限授权,广泛用于第三方登录、服务间资源共享等场景。主要包含四种模式:授权码模式(最安全,适用于Web应用)、简化模式(适用于无后端的前端应用)、密码模式(需高度信任的服务间使用)和客户端模式(服务间内部调用,不涉及用户)。Spring Security中集成OAuth2可实现单点登录与资源保护。