过滤器链加载原理

简介: 本文深入解析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月前
|
前端开发 JavaScript Java
Spring Boot中使用拦截器
本文详解Spring Boot拦截器的原理与使用,涵盖定义、配置、静态资源处理及登录校验、注解控制等实战场景,助你掌握AOP思想在请求拦截中的应用。
|
Java Spring
spring学习笔记(七)HttpMessageConverter
spring学习笔记(七)HttpMessageConverter
527 0
|
11月前
|
SQL 关系型数据库 数据库
分布式事务
本文介绍了分布式事务的概念、典型场景及解决方案。在微服务架构下,一次业务操作需跨多个数据库和远程调用协作完成,传统本地事务无法保证整体一致性。通过Seata框架可实现分布式事务控制,其AT模式无侵入、高性能,基于两阶段提交与undo log实现最终一致;XA模式则提供强一致性但性能较低。文章还结合下单、支付等场景演示了Seata的集成与应用。
|
11月前
|
监控 Java API
Spring Boot中的切面AOP处理
AOP(面向切面编程)旨在分离关注点,将核心业务与辅助逻辑解耦。通过Spring Boot中的@Aspect、@Pointcut、@Before、@After等注解,可实现日志记录、性能监控、事务管理等功能,提升代码模块化与可维护性,灵活应对业务变化。
|
4月前
|
人工智能 缓存 API
阿里云百炼 Token Plan 介绍:Credits统一计量,多模型多工具一站式订阅指南
在AI大模型应用普及的当下,开发者与企业面临着模型选择分散、计费方式复杂、团队管理混乱、成本难以管控等痛点。阿里云百炼推出的Token Plan订阅服务,以Credits为统一计量单位,整合多模态模型与主流AI工具,提供个人版与团队版双版本,覆盖从个人开发者轻量使用到企业团队规模化协作的全场景需求,实现“一份订阅、多模型通用、多工具兼容、统一管理”,大幅简化AI服务使用流程,降低成本与管理门槛。
583 1
|
4月前
|
人工智能 资源调度 开发工具
从 fork 到发布:用 Qoder 重构了一个图床插件
一款 VSCode 图床插件,源码仓库 404、代码陈旧、依赖冗余——但刚好拿来试试 Qoder。先建 Wiki 摸清老代码的坑,再用 Spec 模式驱动重构,中间踩了 Region 格式的坑,最后一句指令搞定 OSS 配置、一行命令打包发布。一次从头到尾的 vibe coding记录
415 0
从 fork 到发布:用 Qoder 重构了一个图床插件
|
3月前
|
Web App开发 Go 开发者
我编写了一个手机遥控在线 PPT 翻页工具【Chrome 免费插件】
这是一款开源免费的Chrome插件,支持腾讯文档、Google Slides和微软在线PPT。手机扫码即变遥控器,实现无线翻页、实时画面同步、演讲备注查看、激光标注、观众互动等功能,无需APP,零延迟、高隐私、全免费。
578 0
|
5月前
|
运维 小程序 数据可视化
小程序开发实测|踩坑无数!游戏陪玩小程序为什么一定要用第三方专业分账系统?
经过多项目实测验证,分账链是目前适配陪玩小程序最贴合、最稳妥的第三方专业分账解决方案。它不是通用型工具,而是针对性适配文娱陪玩、小程序撮合场景的垂直分账系统,兼顾了「低开发成本、全场景适配、合规兜底、高稳定性」四大核心优势。 对于想要快速上线、稳定运营、合规放量、降低运维成本的小程序开发团队,直接接入成熟的垂直专业分账系统,是性价比最高、踩坑最少的技术选型。
599 2
|
5月前
|
数据采集 前端开发 JavaScript
Scrapling:极简高效的 Python 智能爬虫框架
Scrapling:极简高效的 Python 智能爬虫框架
|
数据采集 存储 Web App开发
Python爬虫技巧:设置Cookie永不超时的详细指南
Python爬虫技巧:设置Cookie永不超时的详细指南

热门文章

最新文章