Ldap查询特定于组的所有成员

本文关键字:成员 于组 查询 Ldap | 更新日期: 2023-09-27 18:29:26

我想得到一个属于特定组的用户列表,'groupName'被传递到私有方法中。

 DirectoryEntry de = new DirectoryEntry("LDAP://DC=xxxx,DC=net"); // Root Directory //
 var ds = new DirectorySearcher(de);
 ds.PropertiesToLoad.Add("SAMAccountName");
 ds.PropertiesToLoad.Add("member");
 ds.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))";
 SearchResultCollection AllGroupUsers;     
 AllGroupUsers = ds.FindAll();

查询返回3个属性:-adspath、accountName和member。会员才是我真正追求的。我访问成员属性及其值,如下代码所示:-

 if (AllGroupUsers.Count > 0)
   {
     ResultPropertyValueCollection values = AllGroupUsers[0].Properties["member"];

但是这里发生了一些奇怪的事情。在等号的RHS上,AllGroupUsers的特定成员的值为"CN=Mike Schoomaker R,….."

当在等号的LHS上时,值具有"CN=Mike Schoomaker(OR),……"

我不太确定这怎么可能。。。AllGroupUsers下的每个值都不会发生这种情况。。。我唯一知道的是,它发生在active directory上的外部用户身上。。。有人能告诉我如何解决这个问题并获得实际的firstName、LastName和MiddleInitial吗?

Ldap查询特定于组的所有成员

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    using (var group = GroupPrincipal.FindByIdentity(ctx, "groupName"))
    {
        if (group == null)
        {
            MessageBox.Show("Group does not exist");
        }
        else
        {
            var users = group.GetMembers(true);
            foreach (UserPrincipal user in users)
            {
                //user variable has the details about the user 
            }
         } 
      }
}

要获取用户,而不是组,您应该设置DirectoryEntry对象并使用相应的属性(例如displayNamesngivenNameinitials

示例:

...    
AllGroupUsers = ds.FindAll();
if (AllGroupUsers.Count > 0) {
    ResultPropertyValueCollection values = AllGroupUsers[0].Properties["member"];
    foreach (string s in values) 
    {
        DirectoryEntry u = new DirectoryEntry("LDAP://" + s);  
        Console.WriteLine(u.Properties["displayName"].Value);
    }
}