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.Negotiate
but 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.