I need to get group names for a userDN. I am trying this code but does not work properly as ctx.search() will return only one member for every group. I mean, even though some of my groups have multiple users as members (using member, not memberOf), the search() will return only one.
(I am using OpenLDAP as LDAP server)
In the end, my code will not return all groups for supplied userDN, as will not find all matches.
Thanks for any help.
public Set<String> getLDAPGroupNames(String userDN) throws NamingException {
Set<String> userRoleNames = new HashSet<>();
if (isLDAPUserRepositoryEnabled()) {
for (String roleName : getLDAPGroupNames()) {
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setReturningAttributes(new String[] { "member" });
constraints.setCountLimit(100);
// First input parameter is search bas, it can be "CN=Users,DC=YourDomain,DC=com"
// Second Attribute can be uid=username
LdapContext ctx = getLdapContext();
try {
NamingEnumeration<SearchResult> answer = ctx.search(ldapGroupContextDN, "cn=" + roleName, constraints);
while (answer.hasMore()) {
NamingEnumeration<? extends Attribute> attributes = answer.next().getAttributes().getAll();// FIXME Only returns first of the member entry for the group.
while (attributes.hasMore()) {
Attribute attribute = attributes.next();
if (userDN.equalsIgnoreCase((String) attribute.get()))
userRoleNames.add(roleName);
}
}
} finally {
ctx.close();
}
}
} else
throw new IllegalStateException("Can't return LDAP group names. No LDAP Context enabled.");
return userRoleNames;
}