SpringSecurity的FilterChainProxy注册到Servlet中的原理

1 场景

SpringSecurity起作用的原理依赖于FilterChainProxy类,其本身是个Servlet中的Filter,其中内置了拦截器链来对请求进行层层拦截,因此达到安全验证的目的。

本文主要根据源码分析下,在SpringBoot的环境中springSecurity中的拦截器,如何达到安全验证的目的?

2 相关版本

此处的源码依赖SpringBoot的版本:2.3.3.RELEASE,相关依赖如下:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

3 基本原理

3.1 组件之前的关系

FilterChainProxy作为一个Filter,并没有直接配置在servlet中,而是借助了DelegatingFilterProxy对象进行了一层代理

其中之间的关系如下所示(此图来自spring官网):

1623849087684.png

如上图所示,DelegatingFilterProxy也是Filter,其配置到Servlet的Filter中,对请求进行拦截。

拦截到请求后,执行doFilter方法时,真正执行方法的,是被代理的对象FilterChainProxy(bean的name为springSecurityFilterChain)中的doFilter方法。如下图:

1623930461679.png

实现代码如下:

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 = findWebApplicationContext();
                if (wac == null) {
                    throw new IllegalStateException("No WebApplicationContext found: " +
                                                    "no ContextLoaderListener or DispatcherServlet registered?");
                }
                delegateToUse = initDelegate(wac);
            }
            this.delegate = delegateToUse;
        }
    }

    // 被代理对象(FilterChainProxy)执行真正的doFilter方法
    invokeDelegate(delegateToUse, request, response, filterChain);
}

// 初始化代理对象
protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
    // 此处的targetName值为“springSecurityFilterChain”
    String targetBeanName = getTargetBeanName();
    Assert.state(targetBeanName != null, "No target bean name set");
    // 映射的被代理的bean类型为“FilterChainProxy”,name为“springSecurityFilterChain”
    Filter delegate = wac.getBean(targetBeanName, Filter.class);
    if (isTargetFilterLifecycle()) {
        delegate.init(getFilterConfig());
    }
    return delegate;
}

protected void invokeDelegate(
    Filter delegate, ServletRequest request, ServletResponse response, FilterChain filterChain)
    throws ServletException, IOException {
    // 被代理对象(springSecurityFilterChain),执行真正的doFilter方法
    delegate.doFilter(request, response, filterChain);
}

3.2 为什么借助DelegatingFilterProxy进行代理

使用DelegatingFilterProxy代理的Filter,可以受spring上下文环境管理,相对于传统的Filter,有如下优点:

  • 可以使用spring上下文环境中的bean
  • 可以很方便使用spring加载配置文件
  • 可以用spring管理Filter的生命周期(默认关闭,可设置targetFilterLifecycle为true开启)

4 源码分析

SpringBoot加载FilterChainProxy的代码调用关系如下图:

SpringBoot中SpringGateway的过滤器链加载机制.png

下文将对上图的代码结构图中标记位置①、②等进行详细记录

  • 代码①
private void createWebServer() {
    WebServer webServer = this.webServer;
    ServletContext servletContext = getServletContext();
    if (webServer == null && servletContext == null) {
        ServletWebServerFactory factory = getWebServerFactory();
        // getSelfInitializer调用位置③代码
        this.webServer = factory.getWebServer(getSelfInitializer());
        getBeanFactory().registerSingleton("webServerGracefulShutdown",
                                           new WebServerGracefulShutdownLifecycle(this.webServer));
        getBeanFactory().registerSingleton("webServerStartStop",
                                           new WebServerStartStopLifecycle(this, this.webServer));
    }
    else if (servletContext != null) {
        try {
            // 调用位置②代码
            getSelfInitializer().onStartup(servletContext);
        }
        catch (ServletException ex) {
            throw new ApplicationContextException("Cannot initialize servlet context", ex);
        }
    }
    initPropertySources();
}
  • 代码②
// 代码①中的
getSelfInitializer().onStartup(servletContext);
  • 代码③
public ServletContextInitializerBeans(ListableBeanFactory beanFactory,
            Class<? extends ServletContextInitializer>... initializerTypes) {
    this.initializers = new LinkedMultiValueMap<>();
    this.initializerTypes = (initializerTypes.length != 0) ? Arrays.asList(initializerTypes)
        : Collections.singletonList(ServletContextInitializer.class);
    addServletContextInitializerBeans(beanFactory);
    addAdaptableBeans(beanFactory);
    List<ServletContextInitializer> sortedInitializers = this.initializers.values().stream()
        .flatMap((value) -> value.stream().sorted(AnnotationAwareOrderComparator.INSTANCE))
        .collect(Collectors.toList());
    this.sortedList = Collections.unmodifiableList(sortedInitializers);
    logMappings(this.initializers);
}
  • 代码④
private void addServletContextInitializerBeans(ListableBeanFactory beanFactory) {
        for (Class<? extends ServletContextInitializer> initializerType : this.initializerTypes) {
            for (Entry<String, ? extends ServletContextInitializer> initializerBean : getOrderedBeansOfType(beanFactory,
                    initializerType)) {
                addServletContextInitializerBean(initializerBean.getKey(), initializerBean.getValue(), beanFactory);
            }
        }
    }
  • 代码⑤
private <T> List<Entry<String, T>> getOrderedBeansOfType(ListableBeanFactory beanFactory, Class<T> type,
            Set<?> excludes) {
    String[] names = beanFactory.getBeanNamesForType(type, true, false);
    Map<String, T> map = new LinkedHashMap<>();
    for (String name : names) {
        if (!excludes.contains(name) && !ScopedProxyUtils.isScopedTarget(name)) {
            T bean = beanFactory.getBean(name, type);
            if (!excludes.contains(bean)) {
                map.put(name, bean);
            }
        }
    }
    List<Entry<String, T>> beans = new ArrayList<>(map.entrySet());
    beans.sort((o1, o2) -> AnnotationAwareOrderComparator.INSTANCE.compare(o1.getValue(), o2.getValue()));
    return beans;
}
  • 代码⑥
private void addServletContextInitializerBean(String beanName, ServletContextInitializer initializer,
            ListableBeanFactory beanFactory) {
    if (initializer instanceof ServletRegistrationBean) {
        Servlet source = ((ServletRegistrationBean<?>) initializer).getServlet();
        addServletContextInitializerBean(Servlet.class, beanName, initializer, beanFactory, source);
    }
    else if (initializer instanceof FilterRegistrationBean) {
        Filter source = ((FilterRegistrationBean<?>) initializer).getFilter();
        addServletContextInitializerBean(Filter.class, beanName, initializer, beanFactory, source);
    }
    else if (initializer instanceof DelegatingFilterProxyRegistrationBean) {
        String source = ((DelegatingFilterProxyRegistrationBean) initializer).getTargetBeanName();
        addServletContextInitializerBean(Filter.class, beanName, initializer, beanFactory, source);
    }
    else if (initializer instanceof ServletListenerRegistrationBean) {
        EventListener source = ((ServletListenerRegistrationBean<?>) initializer).getListener();
        addServletContextInitializerBean(EventListener.class, beanName, initializer, beanFactory, source);
    }
    else {
        addServletContextInitializerBean(ServletContextInitializer.class, beanName, initializer, beanFactory,
                                         initializer);
    }
}
  • 代码⑦
private void addServletContextInitializerBean(Class<?> type, String beanName, ServletContextInitializer initializer,
            ListableBeanFactory beanFactory, Object source) {
    this.initializers.add(type, initializer);
    if (source != null) {
        // Mark the underlying source as seen in case it wraps an existing bean
        this.seen.add(source);
    }
    if (logger.isTraceEnabled()) {
        String resourceDescription = getResourceDescription(beanName, beanFactory);
        int order = getOrder(initializer);
        logger.trace("Added existing " + type.getSimpleName() + " initializer bean '" + beanName + "'; order="
                     + order + ", resource=" + resourceDescription);
    }
}
  • 代码⑧
public final void onStartup(ServletContext servletContext) throws ServletException {
    String description = getDescription();
    if (!isEnabled()) {
        logger.info(StringUtils.capitalize(description) + " was not registered (disabled)");
        return;
    }
    register(description, servletContext);
}
  • 代码⑨
// 类AbstractFilterRegistrationBean中的方法
protected String getDescription() {
    Filter filter = getFilter();
    Assert.notNull(filter, "Filter must not be null");
    return "filter " + getOrDeduceName(filter);
}
  • 代码⑩
// 重要
public DelegatingFilterProxy getFilter() {
    return new DelegatingFilterProxy(this.targetBeanName, getWebApplicationContext()) {

        @Override
        protected void initFilterBean() throws ServletException {
            // Don't initialize filter bean on init()
        }

    };
}
  • 代码(11)
protected final void register(String description, ServletContext servletContext) {
    D registration = addRegistration(description, servletContext);
    if (registration == null) {
        logger.info(StringUtils.capitalize(description) + " was not registered (possibly already registered?)");
        return;
    }
    configure(registration);
}
  • 代码(12)
// Filter被加入到servlet环境中
protected Dynamic addRegistration(String description, ServletContext servletContext) {
    Filter filter = getFilter();
    return servletContext.addFilter(getOrDeduceName(filter), filter);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 161,326评论 4 369
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,228评论 1 304
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,979评论 0 252
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,489评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,894评论 3 294
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,900评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,075评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,803评论 0 205
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,565评论 1 249
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,778评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,255评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,582评论 3 261
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,254评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,151评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,952评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,035评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,839评论 2 277

推荐阅读更多精彩内容

  • 本文基于 Spring Security 5.3版本官方文档 一、简介 Spring Security是一个提供身...
    慵懒的阳光丶阅读 570评论 0 0
  • 1.简介 当前绝大多数网站都都存在着用户认证和用户授权这最基本的功能,关于这两个功能概述如下: 用户认证:验证某个...
    秃头猿猿阅读 962评论 0 4
  • 一、 关键词 Authentication:鉴权,我理解为身份认证,是权限验证中的一个特殊的分支。Authoriz...
    ForeverChance阅读 454评论 0 0
  • 前言 看了网上各种关于Spring Security原理解析的文章,大部分都是一上来就贴源码的,我个人觉得一来就贴...
    f310ff9ba986阅读 1,755评论 1 18
  • 表情是什么,我认为表情就是表现出来的情绪。表情可以传达很多信息。高兴了当然就笑了,难过就哭了。两者是相互影响密不可...
    Persistenc_6aea阅读 120,728评论 2 7