简体   繁体   中英

When is Active Directory Auto Detected

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?

When you create a domain PrincipalContext or DirectoryContext without specifying a domain or path, the current context is used. ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM