列出用户所属的所有组的LDAP查询?

3

如果我有一个用户名,我该如何编写LDAP查询来返回用户所属的所有组?

2个回答

4

您是否正在使用.NET 3.5?

如果是的话,请查看这篇优秀的MSDN文章《在.NET Framework 3.5中管理目录安全主体》,该文章展示了.NET 3.5中用于用户和组管理的新功能。

在这种情况下,您需要一个主体上下文(例如您的域):

PrincipalContext domainContext = 
   new PrincipalContext(ContextType.Domain, "YourDomain");

然后你就可以很容易地找到用户:
UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, "username");

"UserPrincipal"对象有一个名为"GetAuthorizationGroups"的方法,用于返回用户所属的所有组:

PrincipalSearchResult<Principal> results = user.GetAuthorizationGroups();

// display the names of the groups to which the
// user belongs

foreach (Principal result in results)
{
    Console.WriteLine("name: {0}", result.Name);
}

很容易,是吧?

在.NET 3.5之前或从其他语言(如PHP、Delphi等)使用“直接”LDAP时,需要更多的工作。

Marc


1

这里有另一种获取组信息的方法:

确保您添加了 System.DirectoryServices 的引用。

DirectoryEntry root = new DirectoryEntry("LDAP://OU=YourOrganizationOU,DC=foo,DC=bar");

DirectoryEntry user = GetObjectBySAM("SomeUserName", root);

if (user != null)
{
  foreach (string g in GetMemberOf(user))
  {
    Console.WriteLine(g);
  }
}

以下方法获取用户输入并返回一个字符串列表,其中包含用户所属的组。
public List<string> GetMemberOf(DirectoryEntry de)
{
  List<string> memberof = new List<string>();

  foreach (object oMember in de.Properties["memberOf"])
  {
    memberof.Add(oMember.ToString());
  }

  return memberof;
}

public DirectoryEntry GetObjectBySAM(string sam, DirectoryEntry root)
{
  using (DirectorySearcher searcher = new DirectorySearcher(root, string.Format("(sAMAccountName={0})", sam)))
  {
    SearchResult sr = searcher.FindOne();

    if (!(sr == null)) return sr.GetDirectoryEntry();
    else
      return null;
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接