UnboundID LDAP SDK: Get all groups for a user

2019-05-06 04:10发布

问题:

Using UnboundID LDAP sdk, how can I get all the LDAP groups a particular user belongs to? (I would really appreciate some example code).

回答1:

I have the same problem. However, the solution by Michael doesn't work for me, since it doesn't work recursively.

Apparently, there is a "magic" AD query that gets all groups recursively, see Find Recursive Group Membership (Active Directory) using C# and How do I filter an LDAP query for groups containing a specific user?

While our AD admin has fetched all groups from the command line using ldifde, I can't get the query to work with UnboundID. Our CN has spaces inside, and UnboundID adds a weird '5c' - but even with a (technical) user without spaces, I don't get any result.


Anyway, here's my working (and unefficient) source code (using Google Guava). I've left out some methods and constants, I think you can guess what the value for the constant OBJECT_CLASS is :-)

  /**
   * Gets the groups for a user which is identified by the filter.
   * @param filter The filter that identifies the user
   * @return The groups for the user
   */
  private List<String> getGroups(final Filter filter) {
    LDAPConnection connection = null;
    try {
      connection = getConnection();

      String userDN = getUserDN(connection, filter);
      if (userDN == null) {
        return Collections.emptyList(); // No user found
      }

      Multimap<String, String> groupsByDN = ArrayListMultimap.create();
      getGroupsRecursively(connection, userDN, groupsByDN);
      Set<String> groups = new HashSet<>(groupsByDN.values());
      for (String dn : groupsByDN.keySet()) {
        // The user is not a group...
        if (!dn.equals(userDN)) {
          DN distinguishedName = new DN(dn);
          for (RDN rdn : distinguishedName.getRDNs()) {
            if (rdn.hasAttribute(CN)) {
              groups.add(rdn.getAttributeValues()[0]);
              break;
            }
          }
        }
      }
      return new ArrayList<String>(groups);
    } catch (LDAPException e) {
      throw new RuntimeException("Can't search roles for " + filter, e);
    } finally {
      if (connection != null) {
        connection.close();
      }
    }
  }

  /**
   * Since LDAP groups are stored as a tree, this fetches all groups for a user, starting with the user's DN and then
   * fetching every group's groups and so on.
   * @param connection The LDAP connection
   * @param distinguishedName The distinguished name for which groups are searched
   * @param groupsByDN Contains a distinguished name as key and its group name as result; keys are only searched once!
   * @throws LDAPSearchException if the LDAP search fails
   */
  private void getGroupsRecursively(final LDAPConnection connection, final String distinguishedName,
      final Multimap<String, String> groupsByDN) throws LDAPSearchException {
    if (!groupsByDN.containsKey(distinguishedName)) {
      Filter groupFilter = Filter.createANDFilter(Filter.createEqualityFilter(OBJECT_CLASS, GROUP),
          Filter.createEqualityFilter(MEMBER, distinguishedName));
      SearchResult result = getSearchResult(connection, groupFilter, CN);
      List<SearchResultEntry> searchResults = result.getSearchEntries();
      for (SearchResultEntry searchResult : searchResults) {
        String groupName = searchResult.getAttributeValue(CN);
        groupsByDN.put(distinguishedName, groupName);
        getGroupsRecursively(connection, searchResult.getDN(), groupsByDN);
      }
    }
  }


回答2:

The function below will work only for the Active Directory since it generates the membership attribute memberOf. If I will found the way for a general LDAP I will add it.

    Entry   userEntry = ldapConnection.getEntry(userDN);

    List<Entry> entryList = new ArrayList();
    String[] memberValues = userEntry.getAttributeValues("memberOf");
    if (memberValues != null) {
        DNEntrySource entrySource = new DNEntrySource(ldapConnection, memberValues);
        while (true) {
            Entry memberEntry = entrySource.nextEntry();
            if (memberEntry == null) {
                break;
            }

            entryList.add(memberEntry);
        }
    }

    return entryList;