2.过滤器链加载原理

简介: 通过分析DelegatingFilterProxy、FilterChainProxy和SecurityFilterChain源码,揭示了Spring Security过滤器链的加载机制:由web.xml中配置的DelegatingFilterProxy通过bean名称springSecurityFilterChain获取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 filterChains;
private FilterChainProxy.FilterChainValidator filterChainValidator;
private HttpFirewall firewall;
//咿!?可以通过一个叫SecurityFilterChain的对象实例化出一个FilterChainProxy对象
//这FilterChainProxy又是何方神圣?会不会是真正的过滤器链对象呢?先留着这个疑问!
public FilterChainProxy(SecurityFilterChain chain) {
this(Arrays.asList(chain));
}
//又是SecurityFilterChain这家伙!嫌疑更大了!
public FilterChainProxy(List 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 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 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的认证操作呢?要完成此功能,首先要有一套自己的页面!

相关文章
|
2月前
|
存储 弹性计算 测试技术
阿里云最便宜云服务器多少钱?轻量38元,云服务器2核2G99元,2核4G199元,续费不涨价
阿里云当前低价云服务器主要有四条线路:38元/年轻量应用服务器秒杀款与68元/年常规款,配置均为2核2G、200M峰值带宽、40GB云盘、不限流量,前者限新用户且需抢购;99元/年ECS经济型e实例,2核2G、3M固定带宽,新老用户均可参与,支持同价续费;199元/年ECS通用算力型u1实例,2核4G、5M固定带宽、80GB云盘,仅限企业认证用户,同样支持续费同价。选型关键不在于价格高低,而在于账号资格、业务场景、带宽模型与续费规则:轻量适合个人博客与测试环境,ECS适合需要标准云能力、稳定带宽和长期使用的项目。对企业用户而言,99元与199元的续费同价方案,往往比一次性低价抢购更具长期价值。
|
3月前
|
人工智能 监控 BI
一文读懂阿里云百炼Token Plan:订阅档位、额度规则、协议兼容、落地踩坑全解析
随着AI Agent、代码智能体、多模态原型开发的快速普及,开发者经常会遇到多平台会员分散、不同模型独立计费、多套API‑Key管理繁琐的现实痛点。文本大模型、图像生成、语音处理、联网工具各自拥有独立计费体系,切换不同基座模型时,需要反复跳转多个平台,维护多组访问密钥,预算统计、用量核算的工作复杂度大幅提升。阿里云百炼Token Plan是面向开发者与团队推出的大模型订阅服务,采用Credits统一抵扣机制,一份订阅权益覆盖文本大模型、图像、视频、语音多模态能力,同时兼容Harness工具集与OpenClaw、Hermes Agent等大量第三方AI编程智能体工具,仅需要一套专属API密钥,就
351 0
|
6月前
|
人工智能 供应链 机器人
2026中国B2B制造业GEO白皮书:从产业洞察到优化实践
生成式AI正在重构B2B制造业采购决策,89%买家使用AI辅助选型。本白皮书覆盖科技制造与传统制造80个细分行业,通过10大标杆案例(生物医药、集成电路、汽车零部件、新能源、环保、智能装备等)和DSS原则(语义深度、数据支持、权威来源),助您将技术参数、认证资质转化为AI信任资产,实现精准获客。
1099 1
|
机器学习/深度学习 人工智能 监控
143_成本优化:Spot实例与预留实例云资源节省计算详解与最佳实践
在云原生时代,成本优化已成为企业IT基础设施管理的核心挑战之一。随着AI和机器学习工作负载的激增,云资源成本占企业IT预算的比例持续上升,如何在保证服务质量的同时实现显著的成本节约,成为技术团队面临的紧迫问题。根据最新的Datadog云成本报告显示,截至2025年,平均有83%的容器支出被闲置资源浪费,而GPU实例支出在过去一年中增长了40%,已占计算成本的14%。在这样的背景下,深入理解和应用Spot实例和预留实例等成本优化策略,对于任何使用云服务的组织都具有重大的经济意义。
984 9
|
开发工具 git 缓存
Git忽略规则.gitignore不生效
在项目开发过程中个,一般都会添加 .gitignore 文件,规则很简单,但有时会发现,规则不生效。 原因是 .gitignore 只能忽略那些原来没有被track的文件,如果某些文件已经被纳入了版本管理中,则修改.gitignore是无效的。
64549 6
|
12月前
|
人工智能 NoSQL 前端开发
Chap03. SpringAI
SpringAI整合多款主流大模型,支持对话、函数调用与RAG等架构,提供统一API简化开发。通过ChatClient封装交互,结合Prompt工程、工具调用与知识检索,可快速构建智能客服、哄哄模拟器、ChatPDF等应用,并支持多模态与持久化扩展,助力AI应用高效落地。
|
12月前
|
敏捷开发 Dubbo Java
需求开发人日评估
本文介绍敏捷开发中关键的工时评估——人日估算方法,涵盖开发、自测、联调、测试及发布各阶段周期参考,提供常见需求如增删改查、Excel导入导出、跨服务调用等典型场景的人日基准,助力团队科学规划迭代进度。
|
12月前
|
SQL 安全 网络协议
常见的网络攻击
恶意软件指具有险恶目的的程序,如病毒、勒索软件、间谍软件等,常通过钓鱼邮件或漏洞入侵系统,窃取数据、破坏功能。网络钓鱼伪装成可信来源骗取敏感信息。中间人攻击在通信中窃听并篡改数据。DDoS攻击以海量流量瘫痪服务,近年呈高频、大体积趋势,结合僵尸网络、加密流量更难防御。SQL注入利用漏洞获取数据库信息,零日攻击则趁补丁未出时下手。DNS隧道则常被用于隐蔽传输数据,形成恶意通道。
|
12月前
|
敏捷开发 Java 测试技术
为什么要单元测试
本文探讨单元测试如何让软件开发提速而非拖慢进度。通过解析测试体系演进、测试金字塔理念,阐述单元测试在提升调试效率、代码质量与研发效能方面的核心价值,揭示“写单测=踩刹车”的认知误区,倡导研发自主保障质量,推动项目高效持续交付。

热门文章

最新文章