spring-security 如何将LDAP验证管理器生成器转换为验证管理器

v9tzhpje  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(138)

我正在使用以下LDAP配置,该配置利用了GlobalAuthenticationConfigurerAdapter

public static class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter {
        @Override
        public void configure(AuthenticationManagerBuilder auth) throws Exception {
            for (String ldapUrl : ldapUrls) { //I have multiple LDAP servers that must be included
                auth.ldapAuthentication()
                        .userSearchFilter("...")
                        .contextSource()
                        .url(ldapUrl + ldapBase)
                        .managerDn(ldapUsername)
                        .managerPassword(ldapPassword);
            }
        }
    }
}

根据以下文档,提供LDAP身份验证Bean的新方法是:
https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter#ldap-authentication LDAP认证

@Bean
AuthenticationManager ldapAuthenticationManager(
        BaseLdapPathContextSource contextSource) {
    LdapBindAuthenticationManagerFactory factory = 
        new LdapBindAuthenticationManagerFactory(contextSource);
    factory.setUserDnPatterns("uid={0},ou=people");
    factory.setUserDetailsContextMapper(new PersonContextMapper());
    return factory.createAuthenticationManager();
}

问题:现在如何将旧配置(包括多个LDAP URL)转换为新bean?
我的意思是,我可以从哪里获得BaseLdapPathContextSource,并将我的LDAP登录凭据和基本URL提供给它?

gajydyqb

gajydyqb1#

由于AuthenticationManager对于每个SecurityFilterChain只有一个示例,因此我认为您必须创建一组AuthenticationProvider,并将它们添加到SecurityFilterChain中。
下面的代码是一个模拟,因为我不确定LdapContextSource是否需要设置更多的属性,如果你想要基本的UserDetailsServiceLdapAuthoritiesPopulator或自定义的东西。

@Bean
public SecurityFilterChain filterChain(HttpSecurity http, List<LdapAuthenticator> ldapAuthenticators) throws Exception
{
    for(LdapAuthenticator authenticator : ldapAuthenticators)
    {
        LdapAuthoritiesPopulator ldapAuthoritiesPopulator = new UserDetailsServiceLdapAuthoritiesPopulator(userDetails);

        http.authenticationProvider(new LdapAuthenticationProvider(authenticator, ldapAuthoritiesPopulator));
    }
}

@Bean
public List<BindAuthenticator> ldapAuthenticator()
{
    List<BindAuthenticator> authenticators = new ArrayList<>();
    for (String ldapUrl : ldapUrls)
    {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(ldapUrl); 
        BindAuthenticator authenticator = new BindAuthenticator(contextSource);
        authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=people", "(uid={0})", ldapContextSource));
        authenticators.add(authenticator);
    }

    return authenticators;
}

相关问题