Using PrincipalContext & PrincipalSearcher to access Active Directory users from separate server

2.7k views Asked by At

I have the following code to retrieve the current active directory users:

public List<DomainContext> GetADUsers(string term=null)
{
    List<DomainContext> results = new List<DomainContext>();
    string ADServerName = System.Web.Configuration.WebConfigurationManager.AppSettings["ADServerName"];

    using (var context = new PrincipalContext(ContextType.Domain, ADServerName))
    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
    {
        var searchResults = searcher.FindAll();

        foreach (Principal p in searchResults)
        {
            if (term == null || p.SamAccountName.ToString().ToUpper().StartsWith(term.ToUpper()))
            {
                DomainContext dc = new DomainContext();
                dc.DisplayName = p.DisplayName;
                dc.UserPrincipalName = p.UserPrincipalName;
                dc.Name = p.Name;
                dc.SamAccountName = p.SamAccountName;

                results.Add(dc);
            }
        }
    }

    return results;
}

My current situation is as follows:

  1. I am working on the development machine, where both the ASP.NET MVC web application and the Active Directory are on the same machine.

  2. I am not passing usernames and password to get the AD users.

So I have the following concerns when I move my ASP.NET MVC web application which contains the above code to my UAT server:

  1. On the UAT server the ASP.NET MVC web application and AD will be on two different machines.
  2. To access the AD from certain machine I might need to send a username and password to the AD server.

So will my original code works if:

  1. The AD and the ASP.NET MVC web application are on different machines?
  2. And if the AD server required passing a user name and password along with?
1

There are 1 answers

4
Wiktor Zychla On

There are two possibilities.

Either you pass the username/password to the PricipalContext or the identity of the application pool has enough priviledges to query the AD and you don't have to provide username/password then.

If the application server is in the AD, the latter is very convenient as there is no username/password in code and/or configuration files. If on the other hand the application server is not in AD, passing username/password in an explicit way is the only possibility for this to work.