在C#中,如何访问Active Directory以获取某个用户所属的组列表?

时间:2010-08-24 04:44:50

标签: c# asp.net active-directory ldap

在C#中,如何访问Active Directory以获取某个用户所属的组列表?

用户详细信息采用以下格式:

"MYDOMAIN\myuser"

我一直关注the instructions from here,但只有我在表单中有用户详细信息时才会有效:

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

所以也许我要问的是,如何从第一个,更短的表格到下面的完全合格的表格?

非常感谢!

2 个答案:

答案 0 :(得分:3)

这可能会有所帮助......

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;
}

答案 1 :(得分:0)

最后,我必须从相反的角度接近它,因为我必须从一个单独的(受信任的)森林中验证成员。所以这是找到给定组成员列表的代码:

/// <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();
}