Search code examples
spring-securityspring-java-configspring-ldap

Spring Security Active Directory


I am trying to do LDAP authentication by Spring Security.

My code...

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

But always return 401 "Bad credentials" What can be the kind of mistake? Perhaps someone has an example with Java config.


Solution

  • it's work ... maybe anybody willbe helpfull.

           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;
    }