2.过滤器链加载原理

简介: 本文深入解析Spring Security核心过滤机制:`DelegatingFilterProxy`通过名称`springSecurityFilterChain`找到`FilterChainProxy`,后者再将多个安全过滤器封装进`SecurityFilterChain`,最终形成完整的过滤链。`DefaultSecurityFilterChain`作为实现类,持有所有安全过滤器列表,实现请求匹配与过滤。层层委托,构建起安全拦截基石。

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的认证操作呢?要完成此功能,首先要有一套自己的页面!

相关文章
|
3月前
|
消息中间件 Java Kafka
消息中间件RabbitMQ(基础)
本章节介绍微服务架构中的消息中间件MQ,重点讲解RabbitMQ的使用。内容涵盖同步与异步通信的区别、RabbitMQ的安装与基本结构、SpringAMQP的集成与应用,以及不同交换机类型(Fanout、Direct、Topic)的消息路由机制,并通过代码示例演示消息发送与接收流程,帮助理解解耦、削峰、异步处理等核心优势。(239字)
178 0
|
3月前
|
监控 Java 测试技术
微服务保护Sentinel
本课程深入讲解微服务中的雪崩问题及其解决方案,重点介绍阿里开源的流量治理组件Sentinel。内容涵盖Sentinel的部署与整合、限流模式(直接、关联、链路)、流控效果(快速失败、预热、排队等待)、熔断降级、线程隔离及授权规则等核心功能,并结合JMeter压测工具进行实战验证,帮助开发者构建高可用的分布式系统。
 微服务保护Sentinel
|
3月前
|
XML Nacos 数据库
Seata的部署和集成
本文介绍Seata TC服务器的部署与微服务集成,包括下载解压、Nacos配置中心设置、数据库表初始化、高可用集群搭建及事务组映射配置,实现分布式事务统一管理。
137 0
|
3月前
|
SQL 关系型数据库 数据库
分布式事务Seata
本章节深入探讨分布式事务问题,涵盖CAP定理与BASE理论,重点学习Seata框架的XA、AT、TCC及SAGA四种事务模式,掌握跨服务事务一致性解决方案,并实践高可用部署架构。
196 0
分布式事务Seata
|
3月前
|
消息中间件 Shell Linux
RabbitMQ部署指南
本文介绍了RabbitMQ的单机与集群部署方案,涵盖Docker环境下镜像安装、DelayExchange插件配置及三种集群模式(普通、镜像、仲裁队列)的实现。重点讲解了镜像模式的高可用特性与仲裁队列的自动副本管理,提升消息系统的可靠性与扩展性。
208 0
RabbitMQ部署指南
|
3月前
|
负载均衡 Java Nacos
Gateway服务网关
网关是微服务架构的统一入口,实现请求路由、权限控制、限流及负载均衡。SpringCloud Gateway基于WebFlux,性能优于Zuul。支持断言与过滤器工厂,可自定义全局过滤器,解决跨域等问题,是微服务流量管控的核心组件。
313 0
|
3月前
|
存储 缓存 Java
SpringCloud(2024)
本文介绍如何在Spring项目中实现自定义注解,结合AOP与过滤器用于日志、权限控制等场景。通过@Target、@Retention等元注解定义注解,利用AOP拦截方法执行,或通过过滤器实现登录验证,提升代码可读性与复用性。
106 0
|
3月前
|
负载均衡 应用服务中间件 Nacos
Nacos配置中心
本章深入讲解Nacos配置中心实战,涵盖配置管理、热更新、共享配置及优先级规则,并通过搭建Nacos集群实现高可用部署,结合Spring Cloud Alibaba实现微服务动态配置,提升系统可维护性与稳定性。
184 0
|
3月前
|
自然语言处理 Java Shell
安装ES、Kibana、IK
本文介绍如何通过Docker部署单节点Elasticsearch与Kibana,并配置IK分词器。内容涵盖网络创建、镜像加载、容器运行、插件安装及分词器扩展词典与停用词设置,同时提供常见启动报错的解决方案,助力快速搭建中文搜索环境。
171 0
|
3月前
|
关系型数据库 应用服务中间件 nginx
容器引擎Docker
Docker是一种容器化技术,通过将应用及其依赖打包成镜像,实现跨环境一致部署。它利用沙箱机制隔离容器,解决开发、测试与生产环境差异问题,相比虚拟机更轻量、高效,显著提升应用交付与运行效率。
129 0
 容器引擎Docker