4

我正在使用带有 Java 配置和 LDAP 身份验证/授权的 Spring Security 3.2.5。

我们需要在 LDAP 中的两个独立树中搜索组。

ou=组

ou=组,ou=webapps,ou=应用程序

我已经搜索并且无法找到有关此主题的任何信息。

这是我当前运行良好的代码:

@Autowired
public void configureGlobal(UserDetailsContextMapper userDetailsContextMapper, LdapContextSource contextSource, AuthenticationManagerBuilder builder) throws Exception {


    builder
    .ldapAuthentication()
        .userDetailsContextMapper(userDetailsContextMapper)
        .contextSource(contextSource)
        .userSearchFilter("cn={0}")
        .userSearchBase("ou=Users")
        .groupSearchBase("ou=groups");


}

我想做这样的事情:

    builder
    .ldapAuthentication()
        .userDetailsContextMapper(userDetailsContextMapper)
        .contextSource(contextSource)
        .userSearchFilter("cn={0}")
        .userSearchBase("ou=Users")
        .groupSearchBase("ou=groups")
        .groupSearchBase("ou=Groups,ou=webapps,ou=Applications");

可以理解的是,这是行不通的。

有人对从哪里开始有任何指示吗?

4

1 回答 1

2

我的解决方案是创建一个org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator可以调用多个LdapAuthoritiesPopulator. 然后LdapAuthoritiesPopulator为我要查询的每个“groupSearchBase”创建一个。

@Autowired
public void configureGlobal(UserDetailsContextMapper userDetailsContextMapper, LdapContextSource contextSource, AuthenticationManagerBuilder builder) throws Exception {

    MultipleLdapAuthoritiesPopulator multipleLdapAuthoritiesPopulator = new MultipleLdapAuthoritiesPopulator(
        new DefaultLdapAuthoritiesPopulator(contextSource, "ou=Groups,ou=webapps,ou=Applications"),
        new DefaultLdapAuthoritiesPopulator(contextSource, "ou=groups"));

    builder
        .ldapAuthentication()
            .ldapAuthoritiesPopulator(multipleLdapAuthoritiesPopulator)
            .userDetailsContextMapper(userDetailsContextMapper) 
            .contextSource(contextSource)
            .userSearchFilter("cn={0}")
            .userSearchBase("ou=Users");
}

class MultipleLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator {
    private List<LdapAuthoritiesPopulator> authoritiesPopulators;

    public MultipleLdapAuthoritiesPopulator(LdapAuthoritiesPopulator...authoritiesPopulators) {
        this.authoritiesPopulators = asList(authoritiesPopulators);
    }

    @Override
    public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
        List<GrantedAuthority> grantedAuthorities = authoritiesPopulators.stream()
            .map(authPopulator -> authPopulator.getGrantedAuthorities(userData, username))
            .flatMap(Collection::stream)
            .collect(Collectors.toList());

        return grantedAuthorities;
    }
}
于 2017-02-24T14:45:50.887 回答