关于java:深入理解-AuthenticationManagerBuilder-源码篇

7次阅读

共计 14792 个字符,预计需要花费 37 分钟才能阅读完成。

咱们持续来撸 Spring Security 源码。

后面和大家分享了 SecurityBuilder 以及它的一个重要实现 HttpSecurity,在 SecurityBuilder 的实现类里边,还有一个重要的分支,那就是 AuthenticationManagerBuilder,AuthenticationManagerBuilder 看名字就晓得是用来构建 AuthenticationManager 的,所以明天咱们就来看一看 AuthenticationManager 到底是怎么构建的。

1. 初步了解

在 Spring Security 中,用来解决身份认证的类是 AuthenticationManager,咱们也称之为认证管理器。

AuthenticationManager 中标准了 Spring Security 的过滤器要如何执行身份认证,并在身份认证胜利后返回一个通过认证的 Authentication 对象。AuthenticationManager 是一个接口,咱们能够自定义它的实现,然而通常咱们应用更多的是零碎提供的 ProviderManager。

1.1 ProviderManager

ProviderManager 是的最罕用的 AuthenticationManager 实现类。

ProviderManager 治理了一个 AuthenticationProvider 列表,每个 AuthenticationProvider 都是一个认证器,不同的 AuthenticationProvider 用来解决不同的 Authentication 对象的认证。一次残缺的身份认证流程可能会通过多个 AuthenticationProvider。

ProviderManager 相当于代理了多个 AuthenticationProvider,他们的关系如下图:

1.2 AuthenticationProvider

AuthenticationProvider 定义了 Spring Security 中的验证逻辑,咱们来看下 AuthenticationProvider 的定义:

public interface AuthenticationProvider {Authentication authenticate(Authentication authentication)
            throws AuthenticationException;
    boolean supports(Class<?> authentication);
}

能够看到,AuthenticationProvider 中就两个办法:

  • authenticate 办法用来做验证,就是验证用户身份。
  • supports 则用来判断以后的 AuthenticationProvider 是否反对对应的 Authentication。

在一次残缺的认证中,可能蕴含多个 AuthenticationProvider,而这多个 AuthenticationProvider 则由 ProviderManager 进行对立治理,具体能够参考松哥之前的文章:松哥手把手带你捋一遍 Spring Security 登录流程。

最罕用的 AuthenticationProvider 实现类是 DaoAuthenticationProvider。

1.3 Parent

每一个 ProviderManager 治理多个 AuthenticationProvider,同时每一个 ProviderManager 都能够配置一个 parent,如果以后的 ProviderManager 中认证失败了,还能够去它的 parent 中继续执行认证,所谓的 parent 实例,个别也是 ProviderManager,也就是 ProviderManager 的 parent 还是 ProviderManager。能够参考如下架构图:

从下面的剖析中大家能够看出,AuthenticationManager 的初始化会分为两块,一个全局的 AuthenticationManager,也就是 parent,另一个则是部分的 AuthenticationManager。先给大家一个论断,一个零碎中,咱们能够配置多个 HttpSecurity(参见 Spring Security 居然能够同时存在多个过滤器链?),而每一个 HttpSecurity 都有一个对应的 AuthenticationManager 实例(部分 AuthenticationManager),这些部分的 AuthenticationManager 实例都有一个独特的 parent,那就是全局的 AuthenticationManager。

接下来,咱们通过源码剖析来验证咱们下面的论断。

本文内容和上篇文章严密相干,如果大家还没看过上篇源码剖析文章,肯定点击超链接先看下。

2. 源码剖析

在上篇文章中,松哥曾经和大家剖析了 SecurityBuilder 的几个常见实现类 AbstractSecurityBuilder、AbstractConfiguredSecurityBuilder、HttpSecurityBuilder,本文对于这几个类我就不反复介绍了。

咱们间接来看 AuthenticationManagerBuilder,先来看它的一个继承关系:

能够看到,【上篇文章】中介绍的全部都是 AuthenticationManagerBuilder 的父类,所以 AuthenticationManagerBuilder 曾经主动具备了其父类的性能。

AuthenticationManagerBuilder 的源码比拟长,咱们来看几个要害的办法:

public class AuthenticationManagerBuilder
        extends
        AbstractConfiguredSecurityBuilder<AuthenticationManager, AuthenticationManagerBuilder>
        implements ProviderManagerBuilder<AuthenticationManagerBuilder> {public AuthenticationManagerBuilder(ObjectPostProcessor<Object> objectPostProcessor) {super(objectPostProcessor, true);
    }
    public AuthenticationManagerBuilder parentAuthenticationManager(AuthenticationManager authenticationManager) {if (authenticationManager instanceof ProviderManager) {eraseCredentials(((ProviderManager) authenticationManager)
                    .isEraseCredentialsAfterAuthentication());
        }
        this.parentAuthenticationManager = authenticationManager;
        return this;
    }
    public InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> inMemoryAuthentication()
            throws Exception {return apply(new InMemoryUserDetailsManagerConfigurer<>());
    }
    public JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcAuthentication()
            throws Exception {return apply(new JdbcUserDetailsManagerConfigurer<>());
    }
    public <T extends UserDetailsService> DaoAuthenticationConfigurer<AuthenticationManagerBuilder, T> userDetailsService(T userDetailsService) throws Exception {
        this.defaultUserDetailsService = userDetailsService;
        return apply(new DaoAuthenticationConfigurer<>(userDetailsService));
    }
    @Override
    protected ProviderManager performBuild() throws Exception {if (!isConfigured()) {logger.debug("No authenticationProviders and no parentAuthenticationManager defined. Returning null.");
            return null;
        }
        ProviderManager providerManager = new ProviderManager(authenticationProviders,
                parentAuthenticationManager);
        if (eraseCredentials != null) {providerManager.setEraseCredentialsAfterAuthentication(eraseCredentials);
        }
        if (eventPublisher != null) {providerManager.setAuthenticationEventPublisher(eventPublisher);
        }
        providerManager = postProcess(providerManager);
        return providerManager;
    }
}
  1. 首先,咱们能够通过调用 parentAuthenticationManager 办法来给一个 AuthenticationManager 设置 parent。
  2. inMemoryAuthentication、jdbcAuthentication 以及 userDetailsService 几个办法松哥在之前的文章中都曾经介绍过了(深刻了解 SecurityConfigurer【源码篇】),作用就是为了配置数据源,这里就不再赘述。
  3. 最初就是 performBuild 办法,这个办法的作用就是依据以后 AuthenticationManagerBuilder 来构建一个 AuthenticationManager 进去,AuthenticationManager 自身是一个接口,它的默认实现是 ProviderManager,所以这里构建的就是 ProviderManager。在构建 ProviderManager 时,一方面传入 authenticationProviders,就是该 ProviderManager 所治理的所有的 AuthenticationProvider,另一方面传入 ProviderManager 的 parent(其实也是一个 ProviderManager)。

整体来说,这段代码还是很好了解的,松哥在之前的文章中和大家介绍过 Spring Security 整合多个数据源,那个时候咱们本人配置 ProviderManager,跟这里的形式相似,具体能够参考:Spring Security 能够同时对接多个用户表?。

不过本人配置有一个问题就是咱们没有配置 ProviderManager 的 parent,没有配置的话,如果以后 ProviderManager 中认证失败的话,就间接抛出失败,而不会去 parent 中再次进行认证了(一般来说也不须要,如果零碎比较复杂的话,可能须要)。

AuthenticationManagerBuilder 还有一个实现类叫做 DefaultPasswordEncoderAuthenticationManagerBuilder,作为外部类别离定义在 WebSecurityConfigurerAdapter 和 AuthenticationConfiguration 中,不过 DefaultPasswordEncoderAuthenticationManagerBuilder 的内容比较简单,重写了父类 AuthenticationManagerBuilder 的几个办法,配置了新的 PasswordEncoder,无他,所以这里我就不列出这个的源码了,感兴趣的小伙伴能够自行查看。然而这并不是说 DefaultPasswordEncoderAuthenticationManagerBuilder 就不重要了,因为在前面的应用中,基本上都是应用 DefaultPasswordEncoderAuthenticationManagerBuilder 来构建 AuthenticationManagerBuilder。

好啦,这就是 AuthenticationManagerBuilder。

那么是什么时候通过 AuthenticationManagerBuilder 来构建 AuthenticationManager 的呢?

这就波及到咱们的老熟人 WebSecurityConfigurerAdapter 了。当然,对于 WebSecurityConfigurerAdapter 自身的初始化过程,松哥在前面会专门写文章介绍,明天咱们次要来看下如何在 WebSecurityConfigurerAdapter 中开启 AuthenticationManager 的初始化的。

2.1 初始化流程

在初始化流程中,松哥得先和大家介绍一个 AuthenticationConfiguration 类。这个类大家能够当作是一个全局被配类来了解,里边都是一些全局属性的配置:

@Configuration(proxyBeanMethods = false)
@Import(ObjectPostProcessorConfiguration.class)
public class AuthenticationConfiguration {
    @Bean
    public AuthenticationManagerBuilder authenticationManagerBuilder(ObjectPostProcessor<Object> objectPostProcessor, ApplicationContext context) {LazyPasswordEncoder defaultPasswordEncoder = new LazyPasswordEncoder(context);
        AuthenticationEventPublisher authenticationEventPublisher = getBeanOrNull(context, AuthenticationEventPublisher.class);

        DefaultPasswordEncoderAuthenticationManagerBuilder result = new DefaultPasswordEncoderAuthenticationManagerBuilder(objectPostProcessor, defaultPasswordEncoder);
        if (authenticationEventPublisher != null) {result.authenticationEventPublisher(authenticationEventPublisher);
        }
        return result;
    }

    @Bean
    public static GlobalAuthenticationConfigurerAdapter enableGlobalAuthenticationAutowiredConfigurer(ApplicationContext context) {return new EnableGlobalAuthenticationAutowiredConfigurer(context);
    }

    @Bean
    public static InitializeUserDetailsBeanManagerConfigurer initializeUserDetailsBeanManagerConfigurer(ApplicationContext context) {return new InitializeUserDetailsBeanManagerConfigurer(context);
    }

    @Bean
    public static InitializeAuthenticationProviderBeanManagerConfigurer initializeAuthenticationProviderBeanManagerConfigurer(ApplicationContext context) {return new InitializeAuthenticationProviderBeanManagerConfigurer(context);
    }

    public AuthenticationManager getAuthenticationManager() throws Exception {if (this.authenticationManagerInitialized) {return this.authenticationManager;}
        AuthenticationManagerBuilder authBuilder = this.applicationContext.getBean(AuthenticationManagerBuilder.class);
        if (this.buildingAuthenticationManager.getAndSet(true)) {return new AuthenticationManagerDelegator(authBuilder);
        }

        for (GlobalAuthenticationConfigurerAdapter config : globalAuthConfigurers) {authBuilder.apply(config);
        }

        authenticationManager = authBuilder.build();

        if (authenticationManager == null) {authenticationManager = getAuthenticationManagerBean();
        }

        this.authenticationManagerInitialized = true;
        return authenticationManager;
    }

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {this.applicationContext = applicationContext;}

    @Autowired
    public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) {this.objectPostProcessor = objectPostProcessor;}

    private static class EnableGlobalAuthenticationAutowiredConfigurer extends
            GlobalAuthenticationConfigurerAdapter {
        private final ApplicationContext context;
        private static final Log logger = LogFactory
                .getLog(EnableGlobalAuthenticationAutowiredConfigurer.class);

        EnableGlobalAuthenticationAutowiredConfigurer(ApplicationContext context) {this.context = context;}

        @Override
        public void init(AuthenticationManagerBuilder auth) {
            Map<String, Object> beansWithAnnotation = context
                    .getBeansWithAnnotation(EnableGlobalAuthentication.class);
            if (logger.isDebugEnabled()) {logger.debug("Eagerly initializing" + beansWithAnnotation);
            }
        }
    }
}
  1. 这里首先构建了一个 AuthenticationManagerBuilder 实例,这个实例就是用来构建全局 AuthenticationManager 的 AuthenticationManagerBuilder,具体的构建过程在上面的 getAuthenticationManager 办法中。不过这里的这个全局的 AuthenticationManagerBuilder 并非总是有用,为什么这么说呢?且看松哥上面的的剖析。
  2. 另外还有一些 initializeXXX 办法,用来构建全局的 UserDetailService 和 AuthenticationProvider,这些办法小伙伴能够作为一个理解,因为失常状况下是不会用到这几个 Bean 的,只有当 getAuthenticationManager 办法被调用时,这些默认的 Bean 才会被配置,而 getAuthenticationManager 办法被调用,意味着咱们要应用零碎默认配置的 AuthenticationManager 作为 parent,而在理论应用中,咱们个别不会应用零碎默认配置的 AuthenticationManager 作为 parent,咱们本人多多少少都会从新定制一下。

这就是 AuthenticationConfiguration 的次要性能,它次要是提供了一些全局的 Bean,这些全局的 Bean 尽管肯定会初始化,然而并非肯定用到。

那么到底什么时候用到,什么时候用不到,这就和 WebSecurityConfigurerAdapter 无关了,在 WebSecurityConfigurerAdapter 中有三个重要的办法波及到 AuthenticationManager 的初始化问题,第一个是 setApplicationContext 办法:

public void setApplicationContext(ApplicationContext context) {
    this.context = context;
    ObjectPostProcessor<Object> objectPostProcessor = context.getBean(ObjectPostProcessor.class);
    LazyPasswordEncoder passwordEncoder = new LazyPasswordEncoder(context);
    authenticationBuilder = new DefaultPasswordEncoderAuthenticationManagerBuilder(objectPostProcessor, passwordEncoder);
    localConfigureAuthenticationBldr = new DefaultPasswordEncoderAuthenticationManagerBuilder(objectPostProcessor, passwordEncoder) {
        @Override
        public AuthenticationManagerBuilder eraseCredentials(boolean eraseCredentials) {authenticationBuilder.eraseCredentials(eraseCredentials);
            return super.eraseCredentials(eraseCredentials);
        }
        @Override
        public AuthenticationManagerBuilder authenticationEventPublisher(AuthenticationEventPublisher eventPublisher) {authenticationBuilder.authenticationEventPublisher(eventPublisher);
            return super.authenticationEventPublisher(eventPublisher);
        }
    };
}

在该办法中,创立了两个简直一摸一样的 AuthenticationManagerBuilder 实例,为什么会有两个呢?第一个 authenticationBuilder 是一个部分的 AuthenticationManagerBuilder,未来会传入 HttpSecurity 中去构建部分的 AuthenticationManager;第二个 localConfigureAuthenticationBldr 则是一个用来构建全局 AuthenticationManager 的 AuthenticationManagerBuilder。

有小伙伴会问了,构建全局的 AuthenticationManager 不是一开始就在 AuthenticationConfiguration 中创立了吗?为什么这里还有一个?是的,以后这个 localConfigureAuthenticationBldr 是能够禁用的,如果禁用了,就会应用 AuthenticationConfiguration 中提供的 AuthenticationManagerBuilder,如果没禁用,就应用 localConfigureAuthenticationBldr 来构建全局的 AuthenticationManager。

另一个办法则是 getHttp 办法:

protected final HttpSecurity getHttp() throws Exception {if (http != null) {return http;}
    AuthenticationEventPublisher eventPublisher = getAuthenticationEventPublisher();
    localConfigureAuthenticationBldr.authenticationEventPublisher(eventPublisher);
    AuthenticationManager authenticationManager = authenticationManager();
    authenticationBuilder.parentAuthenticationManager(authenticationManager);
    Map<Class<?>, Object> sharedObjects = createSharedObjects();
    http = new HttpSecurity(objectPostProcessor, authenticationBuilder,
            sharedObjects);
    // 省略
    return http;
}

在 getHttp 办法中,会首先调用 authenticationManager 办法去获取一个全局的 AuthenticationManager,并设置给 authenticationBuilder 作为 parent,而后在构建 HttpSecurity 时将 authenticationBuilder 传入进去。

那么接下来就是 authenticationManager() 办法到底是怎么执行的了:

protected AuthenticationManager authenticationManager() throws Exception {if (!authenticationManagerInitialized) {configure(localConfigureAuthenticationBldr);
        if (disableLocalConfigureAuthenticationBldr) {
            authenticationManager = authenticationConfiguration
                    .getAuthenticationManager();}
        else {authenticationManager = localConfigureAuthenticationBldr.build();
        }
        authenticationManagerInitialized = true;
    }
    return authenticationManager;
}
protected void configure(AuthenticationManagerBuilder auth) throws Exception {this.disableLocalConfigureAuthenticationBldr = true;}

能够看到,如果 AuthenticationManager 还没初始化,那就先进行初始化。初始化首先调用 configure 办法,默认状况下,configure 办法里边会把 disableLocalConfigureAuthenticationBldr 变量设置为 true,这样接下来就会进入到 if 分支中了。这个 configure 办法不晓得大家有没有感觉眼生?咱们在自定义的 SecurityConfig 配置类中,个别都是要重写该办法的,一旦重写了这个办法,那么 disableLocalConfigureAuthenticationBldr 变量就不会变为 true,仍然是 false,这样在获取 authenticationManager 的时候就会进入到 else 分支中。

如果进入到 if 分支中,意味着开发者并没有重写 configure 办法,AuthenticationManagerBuilder 就应用默认的,大家能够看到,此时就是调用 authenticationConfiguration.getAuthenticationManager() 办法去获取 AuthenticationManager,也就是一开始咱们说的那个全局的配置。

如果开发者重写了 configure 办法,意味着开发者对 AuthenticationManagerBuilder 进行了一些定制,此时就不能持续应用 AuthenticationConfiguration 中配置的默认的的 AuthenticationManager 了,而要依据开发者 的具体配置,调用 localConfigureAuthenticationBldr.build 办法去构建新的 AuthenticationManager。

一言以蔽之,AuthenticationConfiguration 中的配置有没有用上,全看开发者有没有重写 configure(AuthenticationManagerBuilder auth) 办法,重写了,就用 localConfigureAuthenticationBldr 来构建 parent 级别的 AuthenticationManager,没重写,就用 AuthenticationConfiguration 中的办法来构建。

这是表演 parent 角色的 AuthenticationManager 的构建过程,当然,parent 并非必须,如果你没有这个需要的话,也能够不配置 parent。

最初咱们再来看下部分的 AuthenticationManager 是如何构建的,也就是和 HttpSecurity 绑定的那个 AuthenticationManager。

依据后面的介绍,HttpSecurity 在构建的时候就会传入 AuthenticationManagerBuilder,如下:

public HttpSecurity(ObjectPostProcessor<Object> objectPostProcessor,
        AuthenticationManagerBuilder authenticationBuilder,
        Map<Class<?>, Object> sharedObjects) {super(objectPostProcessor);
    Assert.notNull(authenticationBuilder, "authenticationBuilder cannot be null");
    setSharedObject(AuthenticationManagerBuilder.class, authenticationBuilder);
    // 省略
}

传入进来的 AuthenticationManagerBuilder,二话不说就存到 SharedObject 里边去了,这个依据官网的正文,说它是一个在不同 Configurer 中共享的对象的工具,其实你能够了解为一个缓存,当初存进去,须要的时候再取出来。

取出来的办法,在 HttpSecurity 中也定义好了,如下:

private AuthenticationManagerBuilder getAuthenticationRegistry() {return getSharedObject(AuthenticationManagerBuilder.class);
}

在 HttpSecurity 中,但凡波及到 AuthenticationManager 配置的,都会调用到 getAuthenticationRegistry 办法,如下:

public HttpSecurity userDetailsService(UserDetailsService userDetailsService)
        throws Exception {getAuthenticationRegistry().userDetailsService(userDetailsService);
    return this;
}
public HttpSecurity authenticationProvider(AuthenticationProvider authenticationProvider) {getAuthenticationRegistry().authenticationProvider(authenticationProvider);
    return this;
}

最初在 HttpSecurity 的 beforeConfigure 办法中实现构建:

@Override
protected void beforeConfigure() throws Exception {setSharedObject(AuthenticationManager.class, getAuthenticationRegistry().build());
}

至此,无论是全局的 AuthenticationManager,还是部分的 AuthenticationManager,就都和大家捋一遍了。

3. 小结

有的小伙伴可能对这里的全局、部分不是特地了解,我再给大家略微总结一下。

为什么每一个 HttpSecurity 都要绑定一个 AuthenticationManager?

因为在同一个零碎中,咱们能够回配置多个 HttpSecurity,也就是多个不同的过滤器链(参见 Spring Security 居然能够同时存在多个过滤器链?一文),既然有多个过滤器链,每一个申请到来的时候,它须要进入到某一个过滤器链中去解决,每一个过滤器链中又会波及到 AuthenticationProvider 的治理,不同过滤器链中的 AuthenticationProvider 必定是各自治理最为适合,也就是不同的过滤器链中都有一个绑定的 AuthenticationManager,即每一个 HttpSecurity 都要绑定一个 AuthenticationManager。

本文略有难度,可能有点绕,有没看懂的中央,欢送大家留言探讨。

如果小伙伴们感觉有播种,记得点个在看激励下松哥哦~

正文完
 0