Reputation: 27306
I have before me RFC 4515 that provides the String representation of LDAP search filters. I have also looked into the APIs of the UnboundId SDK for Java but it is not clear to me what is the best idiom to use when I expect my query to fetch one, at most LDAP entry. I have thought about using the DN of that entry as the base in the LDAP query but then, filtering makes really no sense and I have to use a contrived nonsense filter that will, be design, evaluate to true for the entry already indicated in the search base. I.e. there seems to be no alwaysTrue filter to use in the protocol.
Upvotes: 2
Views: 3111
Reputation: 11132
If the distinguished name is known, use the distinguished name as the base object, use SearchScope.BASE
, use a filter of (&)
(or objectClass=*
) and provide a list of the attributes the client requires. For example:
// exception handling not shown
final LDAPConnection conn = new LDAPConnection(host,port);
// some broken servers do not understand the legal filter '(&)', if
// your directory is broken in this way, use 'objectClass=*' and
// an equality filter can be created like:
// Filter filter = Filter.createEqualityFilter("objectClass","*");
final SearchRequest req = new SearchRequest(dn,SearchScope.Sub,"(&)",SearchRequest.ALL_USER_ATTRIBUTES);
final SearchResult result = conn.search(req);
final List<SearchResultEntry> entries = result.getSearchEntries();
conn.close();
This will return all user attributes for the entry. The same thing can be accomplished by:
// exception handling not shown
final LDAPConnection conn = new LDAPConnection(host,port);
final SearchResultEntry entry = conn.getEntry(dn);
conn.close();
If the distinguished name is known, the second method is most succinct. There is also a getEntry(String dn,String attributes ...)
method should the client wish to specify a list of attributes to return. If the DN is not known, the client must search for the entry and the distinguished name is returned in the SearchResultEntry
with every search request that returns at least one entry.
As for fetching at most one entry when multiple entries match a filter, the LDAP client must provide a sufficiently tight search scope and filter to narrow the result to the one entry that is required. That is what the filter and scope are for.
Upvotes: 3