Spring 安全活动目录

Spring Security Active Directory

我正在尝试通过 Spring 安全性进行 LDAP 身份验证。

我的代码...

 auth.ldapAuthentication()
            .userSearchFilter("(uid={0})").userSearchBase("ou=TTU")
            .groupSearchFilter("uniqueMember={0}").groupSearchBase("ou=TTU")
            .contextSource(contextSource())
            .passwordCompare()
                .passwordEncoder(new LdapShaPasswordEncoder())
                .passwordAttribute("userPassword");

但总是return 401 "Bad credentials" 会是怎样的错误呢? 也许有人有 Java 配置的例子。

它的工作...也许任何人都会有所帮助。

       auth.authenticationProvider(ldapAuthenticationProvider());
       auth.eraseCredentials(true);



@Bean
public DefaultSpringSecurityContextSource contextSource(){

    DefaultSpringSecurityContextSource contextSource =
            new DefaultSpringSecurityContextSource(Arrays.asList("ldap://url:389/"),"dc=ttu,dc=ru");
    contextSource.setUserDn(userDn);
    contextSource.setPassword(passwordForLDAP);
    contextSource.setReferral("follow");
    return contextSource;
  }

@Bean
public LdapAuthenticationProvider ldapAuthenticationProvider(){
    return new LdapAuthenticationProvider(ldapAuthenticator(),ldapAuthoritiesPopulator());
}

@Bean
public LdapAuthenticator ldapAuthenticator(){
    BindAuthenticator authenticator = new BindAuthenticator(contextSource());
    authenticator.setUserSearch(userSearch());
    return authenticator;
}

@Bean
public DefaultLdapAuthoritiesPopulator ldapAuthoritiesPopulator(){
    DefaultLdapAuthoritiesPopulator ldapAuthoritiesPopulator =
            new DefaultLdapAuthoritiesPopulator(contextSource(),"ou=TTU");
    ldapAuthoritiesPopulator.setSearchSubtree(true);
    ldapAuthoritiesPopulator.setIgnorePartialResultException(true);
    //ldapAuthoritiesPopulator.setGroupSearchFilter("member={0}");
    ldapAuthoritiesPopulator.setRolePrefix("ROLE_");
    ldapAuthoritiesPopulator.setConvertToUpperCase(true);
    return ldapAuthoritiesPopulator;
}

@Bean
public FilterBasedLdapUserSearch userSearch(){
    FilterBasedLdapUserSearch filterBasedLdapUserSearch =
            new FilterBasedLdapUserSearch("","(sAMAccountName={0})",contextSource());
    filterBasedLdapUserSearch.setSearchSubtree(true);
    return filterBasedLdapUserSearch;
}