【问题标题】:C# Active Directory DirectorySearcher is only finding my own userC# Active Directory DirectorySearcher 只找到我自己的用户
【发布时间】:2019-09-18 15:02:17
【问题描述】:

我有一个函数用于查找与给定名称匹配的任何用户的 displayName 和 mail 字段。到目前为止它有效,但它只返回我登录的用户。

我已经尝试过不同版本的DirectorySearcher,像这样:

new DirectorySearcher("LDAP://my.domain");
new DirectorySearcher();
new DirectorySearcher("LDAP://my.domain/(&(objectCategory=person)(objectClass=user)(anr={0}))");

我还尝试了不同的路径格式和身份验证类型。

我的功能:

/// <summary>
/// Returns a Dictionary of Names and Emails that match the given name
/// </summary>
/// <param name="name">Name to search for</param>
/// <param name="domain">Domain to log in to</param>
/// <param name="username">Username for login into AD</param>
/// <param name="pwd">Password for login into AD</param>
/// <param name="count">returns the number of results found</param>
/// <returns>Dictionary containing the Names and Emails of the users matched</returns>
public Dictionary<string, string> GetPersonsEmailsByName(string name, string domain, string username, string pwd, out int count)
{
    count = 0;
    if (String.IsNullOrEmpty(name)) return new Dictionary<string, string>();

    try
    {
        string domainAndUsername = String.Format(@"{0}\{1}", domain, username);
        using (DirectoryEntry root = new DirectoryEntry("LDAP://my.domain", domainAndUsername, pwd, AuthenticationTypes.Delegation))
        {
            DirectorySearcher search = new DirectorySearcher(root);
            search.Filter = String.Format("(&(objectCategory=person)(objectClass=user)(anr={0}))", name);
            search.SearchScope = SearchScope.Subtree;
            search.PropertiesToLoad.Add("displayName");
            search.PropertiesToLoad.Add("mail");
            var dict = new Dictionary<string, string>();

            SearchResultCollection result = search.FindAll();
            count = result.Count;
            foreach (SearchResult sr in result)
            {
                var de = sr.GetDirectoryEntry();
                dict.Add((string)de.Properties["displayName"].Value, (string)de.Properties["mail"].Value);
            }
            return dict;
        } 

    }
    catch (Exception ex)
    {
        throw new Exception("Error obtaining persons: " + ex.Message);
    }

}

这是使用此函数的示例输出:

User: john_doe
Pass:
Auth OK
Name: Mike
Results: 0
Name: carl
Results: 0
Name: jo
Results: 1
John Doe: j_doe@domain.com
Name: john
Results: 1
John Doe: j_doe@domain.com
Name: j
Results: 1
John Doe: j_doe@domain.com
Name:

我所能得到的只是我自己的名字。

提前感谢您的帮助。

【问题讨论】:

  • 显示如何调用此方法的代码示例。你是说无论你作为参数传入什么名字和用户名,你总是得到相同的结果?

标签: c# active-directory ldap directorysearcher


【解决方案1】:

原来都是我的错。我在代码的前面使用另一个函数进行了登录,这在我不知不觉中将我使用的路径变量更改为登录用户的 cn,这就是为什么除了登录用户之外没有给我任何其他结果的原因。

所以这个方法完全可以正常工作!

我很抱歉。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多