When you create a domain PrincipalContext
or DirectoryContext
without specifying a domain or path, the current context is used. i.e. the account the code is executing under. If the code is executing under an account not in a domain an exception will be thrown. This applies weather running in a windows forms app or in a service.
To validate credentials against a domain all you need to do is:
public bool ValidateCredentials(string username, string password)
{
using (var principalcontext = new PrincipalContext(ContextType.Domain))
{
return principalContext.ValidateCredentials(username, password);
}
}
However, this is not the best way to do this for many reasons. For example, ValidateCredentials
can return true even if the user cannot log in due to expired passwords etc. Secondly, there is a much easier way to use active directory single sign-on for desktop applications:
var currentUser = UserPrincipal.Current;
This returns the principal for the current user, there's no need to re-authenticate, windows already did that, and therefore you already know the user is valid.