Joba
Joba

Reputation: 817

Spring LdapRepository returns no results while Spring Security works

My Problem

I am using an LdapRepository to get user information from an Ldap server. This Ldap server is also queried by Spring Security to authenticate user.

My issue is, that Spring Security is able to find and identify users, while I'm unable to find users through my LdapRepository, using the same LdapContextSource. Querying the LdapRepository in any way does not return results (null or empty Lists).

What I have tried

Used ldapsearch command: ldapsearch -x -H ldaps://<domain> -b o=<org> uid=<uid>

Viewing the traffic in Wireshark (using ldap instead of ldaps) looks like no query is executed by the LdapRepository at all, the connection just opens and closes with 0 results.

Relevant code

Configuration of LdapContextSource

@Bean
public LdapContextSource contextSource() {
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl("ldaps://<domain>");
    contextSource.setBase("o=<org>");
    return contextSource;
}

SecurityConfiguration

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final AuthenticationManagerBuilder authenticationManagerBuilder;

    private final LdapContextSource ldapContext;

    public SecurityConfiguration(AuthenticationManagerBuilder authenticationManagerBuilder, LdapContextSource ldapContext) {
        this.authenticationManagerBuilder = authenticationManagerBuilder;
        this.ldapContext = ldapContext;
    }

    @PostConstruct
    public void init() {
        try {
            authenticationManagerBuilder
                    .ldapAuthentication()
                    .contextSource(ldapContext)
                    .userSearchFilter("(uid={0})");
        } catch (Exception e) {
            throw new BeanInitializationException("Security configuration failed", e);
        }
    }
}

UserRepository

@Repository
public interface UserRepository extends LdapRepository<User> {
    User findByUsername(String username);
    List<User> findByUsernameLikeIgnoreCase(String username);
}

User

@Entry(
  objectClasses = {})
public class User {
    @Id
    private Name id;

    @Attribute(name = "uid", readonly = true)
    private String username;

    public Name getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }
}

Upvotes: 1

Views: 1509

Answers (1)

Joba
Joba

Reputation: 817

I found the solution.

Spring seems to assume the objectClass of User is User, if it is not set explicitly. Setting the correct objectClasses fixes this issue.

Upvotes: 1

Related Questions