【问题标题】:How to know if DirectoryEntry is a user or a group?如何知道 DirectoryEntry 是用户还是组?
【发布时间】:2011-06-15 08:08:30
【问题描述】:

嗨,

我有以下代码从当前 AD 创建一棵树:

public static ActiveDirectory GetActiveDirectoryTree(string pathToAD = "")
{
    DirectoryEntry objADAM = default(DirectoryEntry);
    // Binding object. 
    DirectoryEntry objGroupEntry = default(DirectoryEntry);
    // Group Results. 
    DirectorySearcher objSearchADAM = default(DirectorySearcher);
    // Search object. 
    SearchResultCollection objSearchResults = default(SearchResultCollection);
    // Binding path. 
    ActiveDirectory result = new ActiveDirectory();
    ActiveDirectoryItem treeNode;

    // Get the AD LDS object. 
    try
    {
        if (pathToAD.Length > 0)
            objADAM = new DirectoryEntry();
        else
            objADAM = new DirectoryEntry(pathToAD);
        objADAM.RefreshCache();
    }
    catch (Exception e)
    {
        throw e;
    }

    // Get search object, specify filter and scope, 
    // perform search. 
    try
    {
        objSearchADAM = new DirectorySearcher(objADAM);
        objSearchADAM.Filter = "(&(objectClass=group))";
        objSearchADAM.SearchScope = SearchScope.Subtree;
        objSearchResults = objSearchADAM.FindAll();
    }
    catch (Exception e)
    {
        throw e;
    }

    // Enumerate groups 
    try
    {
        if (objSearchResults.Count != 0)
        {
            //SearchResult objResult = default(SearchResult);
            foreach (SearchResult objResult in objSearchResults)
            {
                objGroupEntry = objResult.GetDirectoryEntry();
                result.ActiveDirectoryTree.Add(new ActiveDirectoryItem() { Id = objGroupEntry.Guid, ParentId = objGroupEntry.Parent.Guid, AccountName = objGroupEntry.Name, Type = ActiveDirectoryType.Group, PickableNode = false });

                foreach (object child in objGroupEntry.Properties["member"])
                {
                    treeNode = new ActiveDirectoryItem();
                    var path = "LDAP://" + child.ToString().Replace("/", "\\/");
                    using (var memberEntry = new DirectoryEntry(path))
                    {
                        if (memberEntry.Properties.Contains("sAMAccountName") && memberEntry.Properties.Contains("objectSid"))
                        {
                            treeNode.Id = Guid.NewGuid();
                            treeNode.ParentId = objGroupEntry.Guid;
                            treeNode.AccountName = memberEntry.Properties["sAMAccountName"][0].ToString();
                            treeNode.Type = ActiveDirectoryType.User;
                            treeNode.PickableNode = true;
                            treeNode.FullName = memberEntry.Properties["Name"][0].ToString();

                            byte[] sidBytes = (byte[])memberEntry.Properties["objectSid"][0];
                            treeNode.ObjectSid = new System.Security.Principal.SecurityIdentifier(sidBytes, 0).ToString();

                            result.ActiveDirectoryTree.Add(treeNode);
                        }
                    }
                }
            }
        }
        else
        {
            throw new Exception("No groups found");
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.Message);
    }

    return result;
} 

问题是使用 (var memberEntry = new DirectoryEntry(path)) 将 DomainUsers 作为该树的用户返回,我不确定这是否正确?

假设我存储了 DomainUsers 节点的 sidId,然后将其发送到以下方法:

public static Boolean GetActiveDirectoryName(string sidId,out string samAccountName,out string fullName)
        {
            samAccountName = string.Empty;
            fullName = string.Empty;


            if (sidId != null && sidId.Length > 0)
            {
                var ctx = new System.DirectoryServices.AccountManagement.PrincipalContext(ContextType.Domain, null);
                using (var up = UserPrincipal.FindByIdentity(ctx, IdentityType.Sid, sidId))
                {
                    samAccountName = up.SamAccountName;
                    fullName = up.Name;

                    return true;
                }
            }
            return false;
        }

up 会被设置为空吗?如果我在 AD 中选择另一个用户,那么它工作得很好。我怀疑 DomainUsers 是一个组,但是如何在 DirectoryEntry 上检查这个?

致以最诚挚的问候

【问题讨论】:

    标签: c# .net active-directory


    【解决方案1】:

    在我脑海中浮现:您是否考虑过检查返回结果的架构属性?我认为您可以使用DirectoryEntry.SchemaEntry.Name 轻松地找出一个组。如果您的架构条目是一个组,它应该返回 group

    参考:MSDN: DirectoryEntry.SchemaEntry


    只是出于好奇和上面代码中的一些离题:
     if (pathToAD.Length > 0)
          objADAM = new DirectoryEntry();
     else
          objADAM = new DirectoryEntry(pathToAD);
     objADAM.RefreshCache();
    

    如果Length>0,您不想使用pathToAD 吗?

    【讨论】:

    • 谢谢!奇怪,在我的解决方案中 SchemaEntry.Name 设置为组?不是容器?感谢您的第二次建议!
    • 不客气。好吧,这就是你的 MSDN :) 我自己还没有递归地找到组,所以不知道它已经改变了。谢谢你也告诉我。
    • @ChrisHayes 更新了答案。 group 是正确的返回值,container 用于 OU,这是 MSDN 示例中显示的内容。
    【解决方案2】:

    警告
    接受的答案是 dangerous 使用,因为 DirectoryEntry.SchemaEntry.Name 可能是任何东西。 (详情请参阅here)。

    因此,最简单的方法是检查objectClass,如下所示:

    // For group check
    bool isGroup = entry.Properties["objectClass"]?.Contains("group") == true;
    // For user check
    bool isUser = entry.Properties["objectClass"]?.Contains("user") == true;
    

    附:对于那些想知道我为什么使用== true 的人,请参阅here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      相关资源
      最近更新 更多