如何知道DirectoryEntry是用户还是组?

7

你好,

我有以下代码来从当前的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将被设置为null吗?如果我选择AD中的另一个用户,那么它就可以正常工作。我怀疑DomainUsers是一个组,但我该如何在DirectoryEntry上检查这个组?

最好的问候

2个回答

6
从我现有的知识来看:您考虑过检查返回结果的模式属性吗?我认为您可以轻松地使用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 设置为group,而不是container?感谢您的第二个建议! - Banshee
不客气。这就是MSDN的作用 :) 我自己还没有递归查找组的经历,所以不知道它已经改变了。谢谢你让我知道。 - Maverik
1
@ChrisHayes 更新了答案。group 是正确的返回值,container 是用于组织单位的,这是 MSDN 示例中显示的内容。 - Maverik

3

警告:
接受的答案使用起来是危险的,因为DirectoryEntry.SchemaEntry.Name可能是任何东西。(更多详细信息请参见这里)。

所以,最简单的方法是检查objectClass,像这样:

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

附注:对于那些好奇我为什么使用了 == true 的人,请看这里


1
感谢提供链接和对"== true"的解释。 - Joshua K

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