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

目录
相关文章
|
8月前
|
开发者
业务架构图
本文介绍了业务架构图的核心概念与绘制方法,涵盖业务定义、架构域分类,强调业务架构是技术、应用与数据架构的基础。通过分层、分模块、分功能三步法,梳理业务逻辑,明确模块边界与信息流,提升客户理解与开发效率。
186 0
 业务架构图
|
8月前
|
NoSQL Linux Shell
2-MongoDB单机部署
本文介绍了MongoDB在Windows和Linux系统下的安装、配置与启动方法,包括下载地址、版本选择、解压安装、命令行及配置文件启动方式,并详细说明了如何通过Shell和图形化工具Compass连接数据库。同时提供常见问题解决方案及附件中的各环境安装包链接,便于快速部署使用。
179 0
|
8月前
|
存储 负载均衡 算法
负载均衡算法
本文介绍多种负载均衡算法:随机、轮询、最小活跃数、源地址哈希及一致性哈希。涵盖适用场景、实现原理与代码示例,适用于服务器性能均等或加权情况,强调动态分配与请求稳定性。
194 1
 负载均衡算法
|
8月前
|
安全 Java 数据安全/隐私保护
2.OAuth2.0实战案例
本文介绍基于Spring Boot与Spring Cloud构建OAuth2授权服务的完整流程,涵盖父工程搭建、资源服务器与授权服务器配置,以及授权码、简化、密码和客户端四种模式的测试验证,实现安全的分布式权限管理。
147 1
 2.OAuth2.0实战案例
|
8月前
|
Java 测试技术 Linux
生产环境发布管理
本文介绍大型团队中多环境自动化发布流程,涵盖DEV、TEST、PRE、PROD各环境职责,结合CI/CD平台实现分支管理、一键部署,并通过Skywalking等工具高效排查日志,提升发布效率与系统稳定性。
128 0
生产环境发布管理
|
8月前
|
SQL NoSQL 前端开发
大厂如何解决订单幂等问题
本文详解分布式系统中订单接口幂等性设计:通过唯一订单号与数据库主键约束防止重复下单,结合Redis标识与版本号机制解决ABA问题,确保请求重复时数据一致,适用于各类数据库场景。
166 0
大厂如何解决订单幂等问题
|
8月前
|
运维 Devops 开发工具
生产环境缺陷管理
git-poison基于go-git实现分布式bug追踪,解决多分支开发中bug漏修、漏发问题。通过“投毒-解毒-银针”机制,自动化卡点发布流程,降低协同成本,提升发布安全性与效率,已在大型团队落地应用。
95 0
|
8月前
|
Java Maven
3. 打包
本文介绍Java项目打包为可执行JAR文件的两种方式:一是将所有内容打包进单一JAR,通过Maven配置spring-boot-maven-plugin实现;二是将JAR、依赖与配置文件分离。涵盖配置方法、打包命令(mvn clean package)、运行与停止指令(java -jar、kill -9 pid)等操作步骤。
243 0
 3. 打包
|
8月前
|
存储 安全 小程序
1.认识OAuth2.0
OAuth2.0是一种开放授权标准,允许第三方应用在用户授权下安全访问资源,无需获取用户账号密码。其核心是通过令牌(token)实现有限授权,广泛用于第三方登录、服务间资源调用等场景,支持授权码、简化、密码和客户端四种模式,兼顾安全性与灵活性。
205 0
 1.认识OAuth2.0
|
8月前
|
存储 缓存 Java
自定义注解
本文介绍如何在Spring框架中实现自定义注解,结合AOP与过滤器应用于日志记录、权限控制等场景。通过定义注解、使用@Target和@Retention等元注解,并配合AOP切面或拦截器,实现对方法的增强处理,提升代码可读性与复用性。
145 0

热门文章

最新文章