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

相关文章
|
4月前
|
NoSQL Linux 网络安全
Redis集群部署指南
本章基于CentOS7讲解Redis集群搭建,涵盖单机安装、主从复制、哨兵集群及分片集群的部署与配置,详细演示Redis高可用与分布式架构实践全过程。
|
4月前
|
消息中间件 负载均衡 Linux
RabbitMQ部署指南
本文介绍了RabbitMQ在CentOS7上基于Docker的单机与集群部署方案,涵盖镜像安装、DelayExchange插件配置、普通集群与镜像模式搭建,并详细演示了仲裁队列的使用及集群扩容方法,实现高可用消息队列服务。
|
4月前
|
Java 测试技术 Linux
生产环境发布管理
本文介绍大型团队中多环境自动化发布流程,涵盖DEV、TEST、PRE、PROD各环境职责,结合CI/CD平台实现代码部署与日志追踪,提升发布效率与系统稳定性。
生产环境发布管理
|
4月前
|
安全 Java 数据安全/隐私保护
2.OAuth2.0实战案例
本文介绍基于Spring Boot与Spring Cloud构建OAuth2授权服务的完整流程,涵盖父工程搭建、资源服务器与授权服务器配置、四种授权模式(授权码、简化、密码、客户端)的实现与测试,结合Spring Security实现安全认证,完成分布式系统下的统一权限管理。
 2.OAuth2.0实战案例
|
4月前
|
前端开发 程序员
常见注解及使用说明
本文介绍SpringMVC中@RequestMapping注解的作用及原理,通过注解将HTTP请求映射到控制器方法,实现前后端接口路径对应,并简述@GetMapping等派生注解的封装关系,帮助理解接口定义机制。
 常见注解及使用说明
|
4月前
|
敏捷开发 Dubbo Java
需求开发人日评估
本文介绍敏捷开发中工时评估的关键方法,以“人日”为单位,针对开发、自测、联调、测试及发布各阶段提供参考周期,并列举常见需求如Excel导入导出、增删改查、跨服务调用等的典型人日估算,助力团队科学规划项目进度。
需求开发人日评估
|
4月前
|
Java Maven
3. 打包
本文介绍Java项目打包为可执行JAR的两种方式:一是将所有内容打包进单一JAR,通过Maven配置mainClass并使用`mvn clean package`构建,运行`java -jar`启动;二是将JAR、依赖与配置文件分离,便于管理。同时提供后台运行及停止进程的方法。
 3. 打包
|
4月前
|
存储 安全 前端开发
1.认识OAuth2.0
OAuth2.0是一种开放授权协议,允许第三方应用在用户授权下获取资源访问权限,而无需获取用户账号密码。相比单点登录,其核心是“授权”而非“认证”。它包含四种模式:授权码模式(最安全,适用于Web应用)、简化模式(适用于前端应用)、密码模式(需高度信任)和客户端模式(服务间调用,与用户无关),广泛用于第三方登录和API授权。
 1.认识OAuth2.0
|
4月前
|
存储 安全 数据库
1.RememberMe简介及用法
RememberMe功能并非保存用户名密码,而是通过服务端生成持久化令牌(Token),借助Cookie实现关闭浏览器后仍保持登录状态。勾选“记住我”后,系统在响应头设置remember-me令牌,后续请求自动携带该令牌验证身份。为提升安全性,可将Token存储至数据库并加入二次校验机制,防止令牌泄露带来的安全风险。
|
4月前
|
存储 安全 Java
认证源码分析与自定义后端认证逻辑
本文深入分析Spring Security认证流程,从UsernamePasswordAuthenticationFilter到AuthenticationManager、AbstractUserDetailsAuthenticationProvider,层层剖析认证机制核心原理,并结合自定义UserDetailsService实现数据库认证,完整讲解自定义认证实现步骤与关键代码。
 认证源码分析与自定义后端认证逻辑

热门文章

最新文章