簡體   English   中英

如何知道 DirectoryEntry 是用戶還是組?

[英]How to know if DirectoryEntry is a user or a group?

你好,

我有以下代碼可以從當前 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 上檢查這個?

此致

在我的頭頂上:您是否考慮過檢查返回結果的 Schema 屬性? 我認為您可以通過使用DirectoryEntry.SchemaEntry.Name輕松找到一個組。 它應該返回group ,如果你的模式條目是一組。

參考: MSDN:DirectoryEntry.SchemaEntry


只是出於好奇並且在上面的代碼中有點偏離主題:

 if (pathToAD.Length > 0) objADAM = new DirectoryEntry(); else objADAM = new DirectoryEntry(pathToAD); objADAM.RefreshCache();

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

警告
接受的答案使用起來很危險,因為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;

PS 對於那些想知道為什么我使用== true ,請參閱此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM