过滤器链加载原理

简介: 通过分析DelegatingFilterProxy、FilterChainProxy与SecurityFilterChain源码,揭示了Spring Security过滤器链的加载机制:由web.xml中配置的DelegatingFilterProxy代理,通过名称获取FilterChainProxy实例,再封装多个SecurityFilterChain,最终将15个安全过滤器注入并执行,实现请求的安全控制。

通过前面十五个过滤器功能的介绍,对于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的认证操作呢?要完成此功能,首先要有一套自己的页面!

相关文章
|
4月前
|
SQL 存储 NoSQL
简述关系型与非关系型数据库的区别
关系型数据库基于表结构,支持SQL和事务,易于维护但读写性能差、灵活性不足;非关系型数据库格式灵活、速度快、成本低,适用于高并发场景,但缺乏SQL支持与事务机制,复杂查询较弱。
|
4月前
|
存储 缓存 Java
SpringBoot自动装配机制
本章深入解析SpringBoot自动装配机制,从@SpringBootApplication注解入手,剖析其组合注解原理。重点讲解@EnableAutoConfiguration如何通过@AutoConfigurationPackage实现包扫描、通过AutoConfigurationImportSelector加载spring.factories中的自动配置类,结合@Conditional条件注解实现智能化配置。同时解析@ComponentScan组件过滤机制及自定义排除方式,揭示SpringBoot“约定优于配置”的底层实现逻辑。(238字)
|
4月前
|
存储 关系型数据库 索引
聚簇索引及其优缺点
聚簇索引是一种数据存储方式,InnoDB通过主键构建B+树组织数据,叶子节点即数据页。若无主键,则选非空唯一索引或隐式创建主键。辅助索引(二级索引)需两次查找:先查主键值,再查数据行。优点是查询快,尤其主键排序与范围查询;缺点是插入依赖顺序,更新主键代价高,且易引发页分裂。
|
4月前
|
JSON 安全 Java
SpringBoot鉴权
本文介绍基于Spring Security与JWT实现客户端Token认证的完整方案,涵盖登录鉴权、Token生成与验证、角色权限控制等细节。通过自定义过滤器与认证组件,结合Redis或数据库可扩展实现高效安全的无状态认证体系,适用于Spring Boot微服务架构。
|
4月前
|
关系型数据库 应用服务中间件 Nacos
Nacos配置中心
本章介绍Nacos配置中心的实现,涵盖配置管理、热更新、共享配置及优先级规则,并演示Nacos集群搭建与高可用部署,帮助掌握微服务环境下配置统一管理的核心技能。
|
存储 人工智能 运维
阿里云 Tair 基于 3FS 工程化落地 KVCache:企业级部署、高可用运维与性能调优实践
阿里云 Tair KVCache 团队联合硬件团队对 3FS 进行深度优化,通过 RDMA 流量均衡、小 I/O 调优及全用户态落盘引擎,提升 4K 随机读 IOPS 150%;增强 GDR 零拷贝、多租户隔离与云原生运维能力,构建高性能、高可用、易管理的 KVCache 存储底座,助力 AI 大模型推理降本增效。
|
4月前
|
人工智能 安全 前端开发
AgentScope Java v1.0 发布,让 Java 开发者轻松构建企业级 Agentic 应用
AgentScope 重磅发布 Java 版本,拥抱企业开发主流技术栈。
4098 55
|
4月前
|
SpringCloudAlibaba Java Nacos
SpringCloud概述
Spring Cloud是微服务架构的统一解决方案,弥补了分散技术栈的不足。它具备约定大于配置、组件丰富、开箱即用等特点,支持云原生应用。版本以地铁站命名,避免与子项目冲突。Spring Cloud Alibaba融合阿里系开源组件如Nacos、Sentinel、Seata等,弥补Netflix套件停更短板,提供更完整、经生产验证的微服务生态,成为主流选择。
|
4月前
|
安全 Java 数据安全/隐私保护
SpringSecurity通用权限管理模型
本文介绍ACL、RBAC等常见权限模型。ACL基于对象授权,简单直接;RBAC则通过“用户-角色-权限-资源”模式实现灵活控制,具备最小权限、职责分离、数据抽象三大原则,并衍生出含角色继承与约束的RBAC0-RBAC3系列,助你构建系统化权限认知。(238字)
|
4月前
|
数据库 索引 存储
数据库索引采用B+树不采用B树的原因
B+树所有数据存储于叶子节点,分支仅作索引,便于遍历与范围查询。内部节点不存数据,提升缓存命中率,降低磁盘IO代价。查询路径长度一致,效率稳定,适合数据库索引场景。

热门文章

最新文章