3
votes

The Question

I am looking for a way to filter users from active directory based upon the current logged in users Active Directory Company name (found with the AD profile).

To search AD i am currently using the following code, which returns all users including system accounts -

PrincipalContext context = new PrincipalContext(ContextType.Domain, "mydomain");
var domainUsers = new List<string>();
var userPrincipal = new UserPrincipal(context);

using (var search = new PrincipalSearcher(userPrincipal))
{
    foreach (var user in search.FindAll())
    {
        if (user.DisplayName != null)
        {
            domainUsers.Add(user.DisplayName);
        }
    }
}

I am looking for a way to only return users that match the Company name of the current AD logged in user. ie if the company name was Test123 the search results would only include all other users that belong to the Test123 company.

Background

I am developing an asp.net MVC 2.1 web app that requires a dropdown list of users from active directory.

1

1 Answers

2
votes

Search All users in Active Directory and match against company field.

While iterating through a list of all users found based on the query, you can convert the Principal to DirectoryEntry since Principal doesnt have the information you need. DirectoryEntry has the properties that you can look up and work with, in terms of filtering. Only "company" is used in this example.

    PrincipalContext context = new PrincipalContext(ContextType.Domain, "mydomain");
    var domainUsers = new List<string>();
    var userPrincipal = new UserPrincipal(context);
    string myCompany = "Test123";
    using (var search = new PrincipalSearcher(userPrincipal))
    {
        foreach (Principal user in search.FindAll())
        {
            string usersCompany = ((DirectoryEntry)user.GetUnderlyingObject())?.Properties["company"]?.Value?.ToString();
            if (user.DisplayName != null && usersCompany != null && usersCompany.Equals(myCompany))
            {
                domainUsers.Add(user.DisplayName);
            }
        }
    }

EDIT

For performance reason, I would recommend using DirectorySearcher instead of using PrincipalSearcher. Here is the other version. Search is done before the FindAll() is executed.

    string myCompany = "Test123";
    string searchQuery = $"(&(objectCategory=user)(objectClass=user)(company={myCompany}))";

    // You can define the fields you want retrieved from AD (Noted by @GabrielLuci)
    DirectorySearcher ds = new DirectorySearcher(searchQuery, 
                               new string[] { "DisplayName" }); 
    foreach(SearchResult user in ds.FindAll())
    {
        domainUsers.Add(user.Properties["DisplayName"][0].ToString());
    }