簡體   English   中英

在WPF中使用LDAP在Active Directory中查找特定用戶

[英]Using LDAP in WPF to find specific user in an Active Directory

在WPF中,因此在C#編程語言中,我試圖使用LDAP在Active Directory中查找特定用戶。 我能夠檢查Active Directory中是否存在特定用戶,但是我無法從目錄中檢索該用戶以獲取對其屬性的訪問權限。

我正在使用System.DirectoryServices命名空間。

有沒有辦法實現我要達到的目標,有沒有辦法使用LDAP從AD中檢索特定用戶以檢查其屬性?

編輯:我用來檢查用戶是否在AD中的代碼。 如果用戶在AD中,則返回true;如果找不到用戶,則返回false。 我想知道是否會限制搜索的用戶數量。

bool ContainsUser(string domain, string userName)
        {
            string ldapBase = string.Format("LDAP://{0}", domain);

            using (var entry = new DirectoryEntry(ldapBase))
            {
                using (var searcher = new DirectorySearcher(entry))
                {
                    searcher.Filter = string.Format("(sAMAccountName={0})", userName);
                    return searcher.FindOne() != null;
                }
            }
        }

您應該使用UserPrincipal.FindByIdentity進行調查

例如:

    public static string GetEmailAddressFromActiveDirectoryUserName(string adUserName)
    {
        string email = string.Empty;
        if (!string.IsNullOrEmpty(adUserName))
        {
            using (var pctx = new PrincipalContext(ContextType.Domain))
            {
                using (UserPrincipal up = UserPrincipal.FindByIdentity(pctx, adUserName))
                {
                    return !string.IsNullOrEmpty(up?.EmailAddress) ? up.EmailAddress : string.Empty;
                }
            }
        }
        return email;
    }

看到:

https://docs.microsoft.com/en-us/dotnet/api/system.directoryservices.accountmanagement.userprincipal.findbyidentity?view=netframework-4.8

用於檢查用戶是否存在於AD中或尚未加載用戶屬性的代碼: searcher.FindOne()?.Properties

public class User
{
    public string UserPrincipalName { get; set; }
    public string Name { get; set; }
}

User GetAdUser(string domain, string userName)
{
    string ldapBase = string.Format("LDAP://{0}", domain);

    using (var entry = new DirectoryEntry(ldapBase))
    {
        using (var searcher = new DirectorySearcher(entry))
        {
            searcher.Filter = string.Format("(sAMAccountName={0})", userName);
            var result = searcher.FindOne();
            User user = null;
            if (result != null)
            {
                // result.Properties - list of loaded user properties
                // result.Properties.PropertyNames - list of user property names                
                user = new User
                {
                    UserPrincipalName = result.Properties["userprincipalname"].Cast<string>().FirstOrDefault();
                    Name = result.Properties["name"].Cast<string>().FirstOrDefault();
                }
            }

            return user;
        }
    }
}

暫無
暫無

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

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