过滤器链加载原理

简介: 通过分析DelegatingFilterProxy、FilterChainProxy与SecurityFilterChain源码,揭示了Spring Security过滤器链的加载机制:web.xml中配置的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 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的认证操作呢?要完成此功能,首先要有一套自己的页面!

相关文章
|
7月前
|
存储 缓存 负载均衡
Nacos注册中心
本文详细介绍Nacos的安装部署、服务注册与发现、分级模型、负载均衡策略、权重控制、环境隔离及实例类型等核心功能,涵盖从入门到实战的全流程,助力掌握Nacos在微服务架构中的应用,实现高效服务治理与配置管理。
|
7月前
|
SQL Java 数据库连接
持久层框架MyBatisPlus
MyBatisPlus是MyBatis的增强工具,简化单表CRUD操作,无需编写XML,通过BaseMapper、条件构造器、分页插件等实现高效开发,支持自定义SQL、逻辑删除、枚举与JSON处理,提升开发效率。
|
7月前
|
缓存 NoSQL Java
微服务高频面试题
本课程系统讲解微服务架构核心知识,涵盖SpringBoot与SpringCloud应用、Nacos注册与配置中心、OpenFeign远程调用、Sentinel熔断限流、Gateway网关鉴权、分布式事务Seata、RabbitMQ消息队列、Elasticsearch搜索及Redis缓存等技术,结合实战场景解析服务治理、数据同步与高并发处理方案。
|
7月前
|
关系型数据库 MySQL Java
开发环境搭建
配置开发环境是高效学习的第一步。并配置JDK11。安装Maven 3.8.6,配置本地仓库与阿里云镜像。安装Git并配置用户信息,在IDEA中集成。Fork黑马商城项目至个人Gitee仓库并克隆到本地。使用DataGrip创建hmall数据库,导入SQL脚本,修改application-dev.yaml中的数据库配置。前端通过nginx运行,进入hmall-nginx目录,用命令行启动nginx(start nginx.exe)。访问http://localhost:18080,登录测试系统。确保各服务正常运行,为后续开发打好基础。
|
7月前
|
canal 消息中间件 关系型数据库
配置数据同步环境
配置Canal+RabbitMQ实现MySQL数据同步,通过开启Binlog日志、创建专用用户并授权,部署Canal监听指定表变更,将增量数据实时发送至RabbitMQ指定队列,确保hm-item库中item_sync表的数据变更可被下游服务消费。
|
7月前
|
Java Nacos Maven
Eureka服务注册与发现
本章介绍Eureka服务注册中心的搭建与使用,完成user-service和order-service的服务注册,实现多实例部署。虽Eureka已被SpringCloud逐步淘汰,但其核心思想仍具参考价值,后续将用Nacos替代并深入探讨。
|
7月前
|
存储 Java 关系型数据库
微服务概述
本文对比单体与微服务架构,解析微服务定义、特征及优缺点,涵盖技术选型、部署方案与学习路径,系统介绍微服务实现方式,助力构建高内聚、低耦合的分布式应用体系。(238字)
|
7月前
|
Java 数据库 Sentinel
服务保护、分布式事务 学习目标
本课程深入讲解微服务保护与分布式事务控制,涵盖雪崩问题、熔断降级、限流、线程隔离等核心机制,基于Sentinel实现服务容错;结合Seata实现AT模式的分布式事务管理,掌握CAP原理与实际应用方案。
|
7月前
|
前端开发 程序员
常见注解及使用说明
本文介绍了SpringMVC中@RequestMapping注解的作用及原理,它用于将HTTP请求映射到控制器方法,实现前后端接口路径对应。并通过@GetMapping等派生注解简化开发,提升接口定义效率。
|
7月前
|
存储 XML Apache
序列化
本文深入解析ZooKeeper的序列化机制,重点分析jute包中的核心接口与实现类。通过源码详解InputArchive、OutputArchive、Index和Record四大组件,结合Binary/Csv/Xml三种序列化方式,揭示其在网络通信与数据存储中的应用,并辅以实例演示序列化与反序列化全过程。