0

I'm building an application that will authenticate users via Active Directory. Nothing major, not adding or editing users, just validating credentials. I found many posts on this - some using System.DirectoryServices.AccountManagement (.NET 3.5 and above) or using LDAP DirectoryEntry...

I'm trying to figure out if I have to specify the AD server URL? When I test, I do not need to specify anything?

  1. When is the AD server auto detected? When do I need to specify a URL?

  2. Is there a call I can make to get the auto detected AD server URL?

Mike Turner
  • 471
  • 1
  • 7
  • 22

1 Answers1

1

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.

Ashigore
  • 4,618
  • 1
  • 19
  • 39
  • What are the many reasons? I do not only want to do the current user, so UserPrincipal.Current will not work. I will allow my user to log in as a different user too. What do you recommend? – Mike Turner May 15 '17 at 18:12
  • 1
    How about a diff domain under the same AD? Would this work? PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, otherDomainName); –  May 15 '17 at 18:22
  • 1
    @MikeTurner Then you can use the 1st code example in my answer as long as the current user is part of the domain, if not then specify a domain, username and password to use for authentication checking. – Ashigore May 15 '17 at 21:08
  • @SOS Yes that will work fine. If a trust is in place then the domain still isn't needed though if the username you are checking includes domain information. – Ashigore May 15 '17 at 21:09
  • @Ashigore What are the other reasons that it is best not to do this? – Mike Turner May 16 '17 at 00:16