简体   繁体   中英

In C#, how to access Active Directory to get the list of groups that a certain user belongs to?

In C#, how do i access Active Directory to get the list of groups that a certain user belongs to?

The user details are in the form:

"MYDOMAIN\myuser"

I've been following the instructions from here but they only work if i have the user details in the form:

"LDAP://sample.com/CN=MySurname MyFirstname,OU=General,OU=Accounts,DC=sample,DC=com"

So maybe what i'm asking is, how to get from the first, shorter, form to the fully qualified form below?

Thanks a lot!

This might help...

using System.Collections;
using System.DirectoryServices;

/// <summary>
/// Gets the list of AD groups that a user belongs to
/// </summary>
/// <param name="loginName">The login name of the user (domain\login or login)</param>
/// <returns>A comma delimited list of the user's AD groups</returns>
public static SortedList GetADGroups(string loginName)
{
    if (string.IsNullOrEmpty(loginName))
        throw new ArgumentException("The loginName should not be empty");

    SortedList ADGroups = new SortedList();

    int backSlash = loginName.IndexOf("\\");
    string userName = backSlash > 0 ? loginName.Substring(backSlash + 1) : loginName;

    DirectoryEntry directoryEntry = new DirectoryEntry();
    DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry, "(sAMAccountName=" + userName + ")");

    SearchResult searchResult = directorySearcher.FindOne();
    if (null != searchResult)
    {
        DirectoryEntry userADEntry = new DirectoryEntry(searchResult.Path);

        // Invoke Groups method.
        object userADGroups = userADEntry.Invoke("Groups");
        foreach (object obj in (IEnumerable)userADGroups)
        {
            // Create object for each group.
            DirectoryEntry groupDirectoryEntry = new DirectoryEntry(obj);
            string groupName = groupDirectoryEntry.Name.Replace("cn=", string.Empty);
            groupName = groupName.Replace("CN=", string.Empty);
            if (!ADGroups.ContainsKey(groupName))
                ADGroups.Add(groupName, groupName);
        }
    }

    return ADGroups;
}

In the end, i had to approach it from the opposite angle because i had to validate members from a separate (trusted) forest. So here's the code to find the list of members of a given group:

/// <summary>
/// Finds the users in the given group. Eg groupName=My-Group-Name-Blah
/// returns an array of users eg: DOMAIN\user
/// </summary>
string[] UsersInGroup(string groupName)
{
  List<String> users = new List<string>();

  // First, find the group:
  string query = string.Format("(CN={0})", groupName);
  SearchResult searchResult = new DirectorySearcher(query).FindOne();
  DirectoryEntry group = new DirectoryEntry(searchResult.Path);

  // Find all the members
  foreach (object rawMember in (IEnumerable)group.Invoke("members"))
  {
    // Grab this member's SID
    DirectoryEntry member = new DirectoryEntry(rawMember);
    byte[] sid = null;
    foreach (object o in member.Properties["objectSid"]) sid = o as byte[];

    // Convert it to a domain\user string
    try
    {
      users.Add(
        new SecurityIdentifier(sid, 0).Translate(typeof(NTAccount)).ToString());
    }
    catch { } // Some SIDs cannot be discovered - ignore these
  }

  return users.ToArray();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM