2.过滤器链加载原理

简介: 本文深入解析Spring Security底层过滤机制,揭秘十五个过滤器如何通过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<SecurityFilterChain> filterChains;
    private FilterChainProxy.FilterChainValidator filterChainValidator;
    private HttpFirewall firewall;
    //咿!?可以通过一个叫SecurityFilterChain的对象实例化出一个FilterChainProxy对象
    //这FilterChainProxy又是何方神圣?会不会是真正的过滤器链对象呢?先留着这个疑问!
    public FilterChainProxy(SecurityFilterChain chain) {
        this(Arrays.asList(chain));
    }
    //又是SecurityFilterChain这家伙!嫌疑更大了!
    public FilterChainProxy(List<SecurityFilterChain> 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<Filter> 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<Filter> 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的认证操作呢?要完成此功能,首先要有一套自己的页面!

相关文章
|
2月前
|
存储 JSON NoSQL
3-MongoDB常用命令
本文介绍MongoDB数据库操作,包括创建与删除数据库、集合的显式与隐式创建、文档的增删改查、批量操作、分页查询及排序统计等基本CRUD操作,适用于文章评论数据管理。
|
2月前
|
存储 NoSQL 关系型数据库
4-MongoDB索引知识
MongoDB索引基于B树结构,可高效支持查询,避免全表扫描。主要类型包括单字段、复合、地理空间、文本及哈希索引,适用于不同查询场景,显著提升查询性能。
|
2月前
|
监控 算法 Unix
Thread.sleep(0) 到底有什么用(读完就懂)
本文深入解析Thread.Sleep函数的工作原理,结合操作系统调度机制,揭示Sleep(1000)未必准时唤醒、Sleep(0)却能触发CPU重新竞争的真相,帮助开发者正确理解线程挂起与CPU调度的关系。
|
2月前
|
安全 Java 数据安全/隐私保护
2.通用权限管理模型
本文介绍了ACL和RBAC两种常见的权限模型。ACL通过直接为用户或角色授权,实现简单但管理复杂;RBAC则基于角色分配权限,结构清晰、易于维护,并细分为RBAC0至RBAC3四个等级,逐步引入角色继承与职责分离机制,提升系统安全与灵活性。
|
2月前
|
Java Maven
3. 打包
本文介绍Java项目打包部署的两种方式:一是将所有内容打包进单一JAR文件,通过Maven配置、打包命令及运行指令实现快速启动与后台运行;二是将主JAR、依赖与配置文件分离,提升灵活性与维护性,并提供端口查询与进程终止方法,便于服务管理。
3. 打包
|
2月前
|
NoSQL Linux Shell
2-MongoDB单机部署
本文详细介绍MongoDB在Windows和Linux系统中的安装、配置与启动方法,包括下载地址、版本选择、解压安装、命令行及配置文件启动方式,并介绍Shell连接、图形化工具Compass的使用,以及Linux下的服务管理与防火墙配置,附带各环境安装包下载链接。
2-MongoDB单机部署
|
2月前
|
NoSQL Java 测试技术
5-MongoDB实战演练
本文介绍某头条文章评论系统的设计与实现,基于SpringDataMongoDB构建微服务,完成评论的增删改查、按文章ID查询、分页查询及点赞功能。通过MongoTemplate优化点赞操作,提升性能,并使用索引提高查询效率,整体方案高效且可扩展。
|
2月前
|
存储 安全 Java
6.鉴权
本文介绍基于Spring Security与JWT的客户端Token认证方案,涵盖实现思路、核心代码及完整流程。通过自定义过滤器与认证组件,结合RBAC权限模型,实现安全的Token生成与验签,保护Spring Boot应用接口。
|
2月前
|
SQL 监控 Java
微服务技术栈
本知识库由“油炸小波”精心整理,涵盖微服务技术栈全貌,包括SpringCloud、Dubbo、Zookeeper等核心框架,以及Java基础、JVM、MySQL、MongoDB等关键技术。内容持续更新,聚焦生产发布、缺陷管理、SQL监控、单元测试等实战场景,助力开发者提升技术能力与工程规范。
|
2月前
|
存储 监控 Java
2. 整合切面,参数拦截+过滤
该类基于Spring AOP实现请求参数的前置拦截与日志记录,自动捕获Controller层请求的URL、IP、方法、参数及响应耗时,便于调试与监控,支持后续扩展如数据脱敏或存储。