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

相关文章
|
JSON 小程序 前端开发
微信小程序(二十四)微信小程序富文本编辑器editor
{ "component": true, "usingComponents": {} }
810 0
|
关系型数据库 MySQL 数据库
什么是内连接、外连接、交叉连接、笛卡尔积呢?
什么是内连接、外连接、交叉连接、笛卡尔积呢?
|
12月前
|
安全 Java 数据库
2.自定义认证实现流程
通过实现UserDetailsService接口并自定义用户加载逻辑,结合Spring Security配置,完成基于数据库的用户认证。注册自定义服务类至SecurityConfig,实现登录验证与权限加载,支持灵活扩展ORM框架,提升系统安全性与可维护性。(238字)
|
12月前
|
传感器 算法 安全
支持二次开发的移动机器人平台设备盘点与解析
移动机器人正从封闭走向开放平台化,本文盘点十大支持二次开发的主流设备,涵盖服务、工业、科研及商用场景。重点解析猎户星空豹小秘2的实时混核架构、松灵Scout系列的高开放底盘、Clearpath经典科研平台及思岚Apollo导航验证方案等,展现API化、数字孪生与功能安全并重的技术趋势,助力开发者精准选型。
|
12月前
|
存储 安全 Java
解密电商平台 SSO 单点跨域
本文深入解析电商平台SSO单点登录与跨域问题,涵盖核心概念、流程拆解及实战方案。通过统一认证中心与JWT令牌实现多系统无缝访问,结合CORS解决跨域难题,提升用户体验与系统安全性。
555 1
|
12月前
|
人工智能 JSON API
从MCP到PTC Anthropic回归Code Execution路线,AiPy的范式被再次验证
Anthropic从MCP到Programmatic Tool Calling的演进,实则是对“上下文爆炸”问题的修正,仍属“上下文工程”范畴。而AiPy早于Claude Code提出Python-use范式,主张“Code is Agent”,通过代码直接交互环境,实现“万物互联、万物编程”。相较MCP/PTC依赖预定义工具,Python-use更具扩展性与灵活性,兼容API、包调用及本地执行,早在2024年8月即实现命令级代码执行,领先Skills两月。CodeAct理念与其高度一致,但本质仍是工具注册模式。Python-use范式直击Agent核心:大模型与环境数据的无限连接能力
|
12月前
|
人工智能 开发框架 Java
Java+AI 的终极结合!JBoltAI 框架助力企业快速落地 AI 应用
JBoltAI是专为Java技术栈打造的企业级AI应用开发框架,破解传统系统接入AI成本高、周期长、稳定性差等难题。深度融合主流大模型与向量数据库,提供脚手架代码、场景案例、系统课程与专属支持,助力Java团队快速实现AI转型,让AI应用开发更高效、更稳定、更易落地。(238字)
446 0
|
12月前
|
自然语言处理 搜索推荐 索引
搜索引擎是如何完成短语检索的?
搜索引擎进行短语检索时,首先尝试将整个短语作为关键词在倒排索引中查找。若未命中,则拆分为更细粒度的词(如“极客”“时间”)分别检索,并利用位置信息索引法,通过计算关键词间的最小窗口长度判断 proximity,确保结果中词语位置接近,从而实现精准匹配。
|
12月前
|
Linux 虚拟化 iOS开发
VMware ESXi 8.0U3h macOS Unlocker & OEM BIOS 2.7 Realtek 网卡集成驱动版
ESXi 8.0U3h Realtek 网卡(RTL8111 / RTL8125 / RTL8126 / RTL8127)定制版
1217 0
|
12月前
|
数据采集 领域建模 数据库
领域模型图(数据架构/ER图)
通过四色原型法进行领域建模,提取数据架构核心要素:红色时标原型(MI)表征业务流程节点,绿色参与方-物品原型(PPT)构建实体,黄色角色原型(Role)明确参与主体,蓝色描述原型(DESC)定义属性。基于风控系统流程,逐步构建领域模型,最终提炼出ER图,清晰展现实体间一对一、一对多、多对多关系,实现从业务到数据模型的精准转化。(238字)

热门文章

最新文章