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

Active directory LDAP查询以列出用户所属的所有组?,active-directory,ldap,active-directory-group,Active Directory,Ldap,Active Directory Group,给定一个用户名,我如何编写一个LDAP查询来返回该用户所属的所有组 你在.NET 3.5上吗 如果是这样,请查看这篇优秀的MSDN文章,它展示了.NET3.5中用户和组管理的新功能 在这种情况下,您需要一个主体上下文(例如,您的域): 然后您就可以很容易地找到用户: UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, "username"); “UserPrincipal”对象有一个名为“GetAuthoriz

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

你在.NET 3.5上吗

如果是这样,请查看这篇优秀的MSDN文章,它展示了.NET3.5中用户和组管理的新功能

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

然后您就可以很容易地找到用户:

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);
}
PrincipalSearchResult results=user.GetAuthorizationGroups();
//显示用户要访问的组的名称
//用户属于
foreach(结果中的主要结果)
{
WriteLine(“名称:{0}”,result.name);
}
很简单吧

在3.5之前的.NET中,或者在其他语言(PHP、Delphi等)中的“直接”LDAP中,需要做更多的工作


Marc

以下是获取组信息的另一种方法:

确保添加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;
  }
}
public List GetMemberOf(DirectoryEntry de)
{
List memberof=新列表();
foreach(de.Properties[“memberOf”]中的对象oMember)
{
memberof.Add(oMember.ToString());
}
返回成员;
}
public DirectoryEntry GetObjectBySAM(字符串sam,DirectoryEntry根目录)
{
使用(DirectorySearcher searcher=newdirectorysearcher(root,string.Format(((sAMAccountName={0})”,sam)))
{
SearchResult sr=searcher.FindOne();
如果(!(sr==null))返回sr.GetDirectoryEntry();
其他的
返回null;
}
}
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;
  }
}