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

时间:2019-05-07 19:56:15

标签: c# wpf active-directory ldap

在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;
                }
            }
        }

2 个答案:

答案 0 :(得分:1)

您应该使用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

答案 1 :(得分:0)

用于检查用户是否存在于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;
        }
    }
}