2.过滤器链加载原理

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

相关文章
|
9月前
|
运维 安全 Devops
生产环境缺陷管理
git-poison基于go-git实现分布式bug追溯,解决多分支开发中bug漏修、漏发等协同难题。通过“投毒-解毒-银针”机制,自动化卡点发布流程,降低沟通成本,避免人为失误,已在大型团队落地一年,显著提升发布安全与效率。
|
9月前
|
SQL Java 数据库连接
持久层框架MyBatisPlus
MyBatisPlus是MyBatis的增强工具,简化单表CRUD操作,无需编写XML即可实现增删改查。通过继承BaseMapper、使用Wrapper条件构造器、分页插件等功能,大幅提升开发效率。支持自定义SQL、逻辑删除、枚举与JSON处理,并提供代码生成器和通用Service层封装,广泛应用于企业级项目中。
|
9月前
|
Java 测试技术 Linux
生产环境发布管理
本文介绍大型团队如何通过自动化部署平台实现多环境(dev/test/pre/prod)发布管理,涵盖各环境职责、基于Jenkins+K8S的CI/CD流程、分支可视化操作、容器化部署机制及日志排查方案,提升发布效率与系统稳定性。
|
9月前
|
JSON 缓存 前端开发
什么是跨域
CORS(跨域资源共享)是W3C标准,允许浏览器向跨源服务器发起XMLHttpRequest请求,突破AJAX同源限制。需浏览器和服务器共同支持,主流浏览器均已兼容。通信过程由浏览器自动完成,开发者无需特殊处理。请求分为简单和非简单两类,后者会先发送OPTIONS预检请求确认权限。服务器通过设置Access-Control-Allow-Origin等头部字段控制跨域访问。相比仅支持GET的JSONP,CORS支持所有HTTP方法,更灵活安全。
|
9月前
|
Java Shell 测试技术
Jmeter快速入门
JMeter是基于JDK的性能测试工具,需先安装并配置JDK。下载解压后,通过双击或命令行启动,注意启动较慢且不可关闭黑窗口。可设置中文语言(临时或修改jmeter.properties永久生效)。基本使用包括创建线程组、添加HTTP取样器、配置监听器(如结果树、汇总报告)以查看测试结果。
|
9月前
|
存储 负载均衡 算法
负载均衡算法
负载均衡算法包括随机、轮询、最小活跃数、源地址哈希与一致性哈希。随机可加权提升性能利用,轮询实现顺序调用,最小活跃数动态分配请求,源地址哈希保证IP固定路由,一致性哈希减少节点变动影响,适用于分布式系统中高效流量调度。(239字)
|
9月前
|
敏捷开发 Dubbo Java
需求开发人日评估
本文介绍敏捷开发中工时评估的关键——人日估算方法,涵盖开发、自测、联调、测试及发布各阶段周期参考,并提供常见需求如增删改查、导入导出、跨服务调用等的典型人日参考,助力团队科学规划迭代。
|
9月前
|
存储 数据库
数据库设计三范式
第一范式要求字段原子性,不可再分;第二范式消除部分依赖,主键确定所有非主键;第三范式消除传递依赖。三者旨在减少数据冗余、提升维护效率,但实际设计需结合业务权衡,不必拘泥范式。
|
9月前
|
SQL 安全 网络协议
常见的网络攻击
恶意软件指具有险恶意图的程序,如病毒、勒索软件、间谍软件等,常通过钓鱼邮件或漏洞入侵系统,窃取数据、破坏系统或加密文件勒索。网络钓鱼伪装成可信来源骗取敏感信息。中间人攻击则在通信中窃听或篡改数据。DDoS攻击利用大量流量瘫痪系统,近年呈高频、大体积趋势,常见于僵尸网络和L7层攻击。SQL注入通过输入恶意代码获取非法数据访问权限。零日攻击利用未修复漏洞发起突击。DNS隧道则滥用DNS协议传输隐蔽数据,用于数据外泄或远程控制。各类攻击日益复杂,需综合防御。
|
9月前
|
SQL 安全 关系型数据库
了解SQL注入
SQL注入是利用Web应用输入验证缺陷,将恶意SQL代码注入数据库查询的攻击方式。可导致身份绕过、数据泄露、篡改甚至系统命令执行。常见于登录框等用户输入场景,通过构造特殊字符如单引号、注释符改变SQL逻辑。防御需结合输入验证、参数化查询与错误信息管控,开发与运维协同防护。

热门文章

最新文章