Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lookup user in ActiveDirectory by email address

How can I query an ActiveDirectory user by email address? A given user can have multiple emails such as both [email protected] and [email protected]. For a given email, how can I get back the A/D user?

I'm programming in C#.

like image 842
David Thielen Avatar asked Sep 06 '13 12:09

David Thielen


1 Answers

You can search your AD with following code:

    DirectoryEntry adEntry = null;

    private void SetADInfoAndCredentials()
    {
        adEntry = new DirectoryEntry("LDAP://" + ad_textBox.Text);
        adEntry.Username = user_textBox.Text;
        adEntry.Password = pw_textBox.Text;
    }

    private void SearchForMailInAD()
    {
        DirectorySearcher adSearcher = new DirectorySearcher(adEntry);
        adSearcher.Filter = ("mail=" + mail_textBox.Text);
        SearchResultCollection coll = adSearcher.FindAll();
        foreach (SearchResult item in coll)
        {
            foundUsers_listBox.Items.Add(item.GetDirectoryEntry());
        }
    }

€: This will search for the mail address in proxyAddresses which hosts all mail addresses

    public static SearchResultCollection FindAccountByEmail(string pEmailAddress)
    {
        string filter = string.Format("(proxyaddresses=SMTP:{0})", email);

        using (DirectoryEntry gc = new DirectoryEntry("LDAP:"))
        {
            foreach (DirectoryEntry z in gc.Children)
            {
                using (DirectoryEntry root = z)
                {
                    using (DirectorySearcher searcher = new DirectorySearcher(root, filter, new string[] { "proxyAddresses", "objectGuid", "displayName", "distinguishedName" }))
                    {
                        searcher.ReferralChasing = ReferralChasingOption.All;
                        SearchResultCollection result = searcher.FindAll();

                        return result;
                    }
                }
            }
        }
        return null;
    }
like image 155
Daniel Abou Chleih Avatar answered Oct 12 '22 13:10

Daniel Abou Chleih