Search code examples
c#asp.netcross-domaindirectoryservices

Cross Domain Authentication using DirectoryServices


I need to create a method for my intranet web application that will authenticate a user using DirectoryServices, either against a default domain, or a user specified one.

On my login form the user will be able to either give there credentials in the form of "username" and "password" or "domain\username" and "password" The first case can be used when the user is in the same domain as the webserver and is quite straightfoward. The code I use is:

 string domain = "";
 // Code to check if the username is in form of "domain\user" or "user"
 string username = ParseUsername(username, out domain);
 if(domain == "")
    domain = defaultDomain;

 PrincipalContext context = new PrincipalContext(ContextType.Domain, domain, username, password); 
 bool IsAuthenticated = context.ValidateCredentials(username, password)

I pass the username and password to the PrincipalContext constructor in order to bind the call in cases where I try to access another domain.

For the local domain the code works fine. However when I try to check against another domain that is being specified through the username, then I get a "Server could not be contacted" error.

I also tried using different ContextOptions such as ContextOptions.SimpleBind or ContextOptions.Negotiatebut I always seem to be getting the same result.

I need to implement this, since the application is being shipped to various customers, with either single domain or multiple domain environments. Is there something else I should specify in cases of "remote" domains? The code needs to be flexible since this will be deployed in various environments.

Thanks

EDIT: I must point out, that I prefer to do it using DirectoryServices.AccountManagement and PrincipalContext in order to take advantage of other functionality it provides as well.

Also, I must mention that for my tests, my Dev machine is on a 10.0.0.* network and the second domain I test against is on a 10.0.1.*. I have a route and all, and I can succesfuly connect using an ldap client, so the question is why I cannot connect to the domain via my asp.net application.


Solution

  • I have come up with this solution to the problem.

    In order to support multiple domains, either in trust relationships or even in isolated networks, first of all I added a NameValueCollection in my web.config to list the domains and their domain controllers.

      <domains>
        <add key="domain1" value="10.0.0.1"/>
        <add key="domain2" value="10.0.1.11"/>
      </domains>
    

    (more info on the configuration addition in this so question)

    Then the next step was to read the domain from the User's credentials in the way I mention in the question. Having gotten the domain I try to lookup the according domain controller from the configuration values, in order to get the proper LDAP connection string. So my method is this:

    private string GetLDAPConnection(string a_Domain, string a_Username, string a_Password)
    {
        // Get the domain controller server for the specified domain
        NameValueCollection domains = (NameValueCollection)ConfigurationManager.GetSection("domains");
        string domainController = domains[a_Domain.ToLower()];
    
        string ldapConn = string.Format("LDAP://{0}/rootDSE", domainController);
    
        DirectoryEntry root = new DirectoryEntry(ldapConn, a_Username, a_Password);
        string serverName = root.Properties["defaultNamingContext"].Value.ToString();
        return string.Format("LDAP://{0}/{1}", domainController, serverName);
    }
    

    Once I get back the proper connection string I make a new call in order to authenticate the user, by addressing the proper LDAP

        ...
        string ldapConn = GetLDAPConnection(domain, username, a_Password);                             
        DirectoryEntry entry = new DirectoryEntry(ldapConn, username, a_Password);        
    
        try
        {
            try
            {
                object obj = entry.NativeObject;
            }
            catch(DirectoryServicesCOMException comExc)
            {
                LogException(comExc);
                return false;
            }
    
            DirectorySearcher search = new DirectorySearcher(entry);
            search.Filter = string.Format("(SAMAccountName={0})", username);
            search.PropertiesToLoad.Add("cn");
            SearchResult result = search.FindOne();
    

    From this point on I can also perform all the other queries I want such as the user's group membership etc.

    Since the call to the remote domains needs to be bound to a user, I use the "calling" users credentials. This way the user get's authenticated and the Call is bound to the specific user. Furthermore, I specify a "default" domain, for cases where users provide their credentials without specifying the domain.

    I did not manage to this however using the PrincipalContext as I wanted, but on the bright side, this solution is also applicable for older .NET 2.0 applications as well.

    I am not sure that this is the best solution to the problem, however it seems to work in the tests we have so far performed.