过滤器链加载原理

简介: 本文深入解析Spring Security核心过滤器链原理,重点剖析DelegatingFilterProxy如何通过代理模式加载springSecurityFilterChain,结合FilterChainProxy与SecurityFilterChain源码,揭示十五个安全过滤器的初始化及执行流程,帮助理解框架底层机制。

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月前
|
安全 数据安全/隐私保护 微服务
什么是权限管理
权限管理包含认证与授权两大核心:认证确认用户身份(如登录),授权则根据角色分配访问权限,确保系统安全。常见模型有ACL、RBAC等,通过角色叠加实现菜单级控制,保障数据安全与操作合规,是系统安全的基石。
什么是权限管理
|
2月前
|
负载均衡 Java 应用服务中间件
微服务网关与配置中心
本文介绍了微服务架构下的网关路由与鉴权机制,重点讲解使用Spring Cloud Gateway实现请求路由、负载均衡及JWT身份校验。通过Nacos实现服务发现,网关统一处理前端请求,解决多入口问题,并在全局过滤器中实现用户鉴权,保障系统安全。
|
2月前
|
JSON Java API
Feign远程调用
本文介绍了如何使用Feign替代RestTemplate实现微服务间的HTTP调用,涵盖依赖引入、注解配置、自定义日志、连接池优化及代码抽取等实践。通过Feign可简化远程调用,提升开发效率,并结合最佳实践实现代码复用与解耦。
|
2月前
|
前端开发 程序员
常见注解及使用说明
`@RequestMapping`用于定义控制器中处理请求的接口路径,实现前后端对接。通过指定URL路径,如`/staff/add`,使前端能准确访问对应接口。其派生注解如`@GetMapping`、`@PostMapping`等为简化常用HTTP方法而封装,本质仍基于`@RequestMapping`。
常见注解及使用说明
|
2月前
|
安全 Java 数据安全/隐私保护
认识SpringSecurity
SpringSecurity是Java领域主流的安全框架,核心功能包括认证、鉴权及防护常见攻击。支持表单、OAuth2、JWT等多种认证方式,基于过滤器链实现灵活权限控制,并提供CSRF、会话固定等安全防护机制。
|
2月前
|
负载均衡 Java 数据安全/隐私保护
Gateway服务网关
网关是微服务架构的统一入口,核心功能包括请求路由、权限控制、限流及负载均衡。通过Spring Cloud Gateway可实现高效路由转发与过滤器处理,支持跨域配置,提升系统安全与性能。
Gateway服务网关
|
2月前
|
存储 安全 小程序
认识OAuth2.0
OAuth2.0是一种开放授权标准,允许第三方应用在用户授权下安全访问资源,无需获取用户账号密码。其核心是通过令牌(token)实现权限控制,广泛用于第三方登录、服务间资源调用等场景,支持授权码、简化、密码和客户端四种模式,保障系统安全与用户体验。
认识OAuth2.0
|
Java Docker Windows
spring boot整合Minio
spring boot整合Minio
407 0
|
2月前
|
前端开发 安全 Java
自定义认证前端页面
本文介绍Spring Security基础配置:前端login.html页面设置,后端新增接口与SecurityConfig安全配置,实现表单登录认证,包括登录页、接口权限、CSRF关闭等,并通过访问/demo/index验证登录跳转流程。
|
2月前
|
安全 Java 应用服务中间件
实现权限管理的技术
本文介绍了权限管理的常见技术选型,对比了Apache Shiro、Spring Security及自定义ACL的优缺点。Shiro轻量易用但安全性较弱;Spring Security功能强大但配置复杂;自定义ACL灵活但维护成本高,适合特定项目需求。