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月前
|
安全 Java 数据安全/隐私保护
2.OAuth2.0实战案例
本文介绍基于Spring Boot与Spring Cloud构建OAuth2授权服务的完整流程,涵盖父工程搭建、资源服务器与授权服务器配置,以及授权码、简化、密码和客户端四种模式的测试验证,实现安全的分布式权限管理。
 2.OAuth2.0实战案例
|
2月前
|
敏捷开发 Java 测试技术
为什么要单元测试
本文探讨单元测试在现代软件开发中的核心价值,打破“写单测费时误事”的误解。通过剖析测试体系演进、测试金字塔理念及谷歌等大厂实践,阐明单元测试如何提升代码质量、加速迭代、增强重构信心,并揭示“冰激凌筒”等反模式风险。倡导研发自主测试,推动软件从“爬行”迈向“奔跑”。
 为什么要单元测试
|
2月前
|
安全 Java 数据安全/隐私保护
2.通用权限管理模型
本文介绍了ACL和RBAC两种常见的权限模型。ACL通过直接为用户或角色授权实现访问控制,简单直观;RBAC则基于角色分配权限,解耦用户与权限关系,更易维护。文中还详解RBAC0-3的演进,涵盖角色继承、职责分离等核心概念,帮助构建系统化权限认知。
 2.通用权限管理模型
|
2月前
|
存储 缓存 Java
自动装配机制
本文深入解析SpringBoot自动装配机制,围绕@SpringBootApplication注解展开,剖析其组合注解中的@ComponentScan、@SpringBootConfiguration与@EnableAutoConfiguration核心原理,详解元注解作用及自动配置类如何通过spring.factories实现自动化加载与组件过滤。
 自动装配机制
|
2月前
|
存储 安全 Java
6.鉴权
本文介绍基于Spring Security与JWT的客户端Token认证方案,涵盖实现思路、核心代码及完整流程。通过自定义过滤器与认证逻辑,结合RBAC权限模型,实现安全的Token生成、校验与访问控制,保护Spring Boot应用接口。
 6.鉴权
|
2月前
|
Java 应用服务中间件 网络安全
Java基础 Eclipse运行SSM/SSH项目教程
本文介绍了Eclipse环境下Java Web项目的运行与配置流程,涵盖JDK、Tomcat等基础软件安装,项目导入及服务器绑定方法,并提供SSH/SSM框架案例与常见错误解决方案。
Java基础 Eclipse运行SSM/SSH项目教程
|
2月前
|
前端开发 程序员 开发者
常见注解及使用说明
本文介绍了SpringMVC中@RequestMapping注解的作用与原理,讲解其如何将前端HTTP请求映射到后端控制器方法,并列举了常用衍生注解如@GetMapping、@PostMapping等,帮助开发者理解接口路径的定义机制,实现前后端对接。
|
2月前
|
Java
@Inherited
@Inherited 是 Java 中的元注解,用于修饰自定义注解,使其在类继承中可被子类继承。当某注解标注了 @Inherited,且应用于父类时,子类会自动继承该注解。但此机制仅适用于类的继承,不适用于接口继承或类实现接口的情况。
|
2月前
|
存储 安全 Java
认证源码分析与自定义后端认证逻辑
本文深入分析Spring Security认证流程,从UsernamePasswordAuthenticationFilter到AuthenticationManager及AbstractUserDetailsAuthenticationProvider源码,详解认证机制,并指导如何通过实现UserDetailsService完成自定义数据库认证,最终实现安全控制。
|
2月前
|
前端开发 安全 Java
1.自定义认证前端页面
本文介绍Spring Security前后端整合实现登录认证的完整流程。前端提供login.html页面,后端通过HelloController定义接口,SecurityConfig配置类设置权限规则、表单登录及CSRF关闭等。启动后访问/demo/index会自动跳转至登录页,输入用户名密码验证成功后返回接口数据,完成安全拦截与认证流程。