Authenticating with the help of System.DirectoryServices.AccountManagement

With the help of System.DirectoryServices.AccountManagement (available from .NET Framework 4.0) authenticating users against Microsoft Active Directory has become a lot simpler.

Compare the below code

public static bool IsAuthenticated( string domain, string username, string pwd ) {
    using ( PrincipalContext pc = new PrincipalContext( ContextType.Domain, domain) ) {
        return pc.ValidateCredentials( username, pwd );
    }
}

to what you have to do previously

public static bool IsAuthenticated(string domain, string username, string pwd) {
    string domainAndUsername = username + "@" + domain;
    string _path = "LDAP://mydcserver.com:389/DC=ad,DC=mydcserver,DC=com";
    DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

    try {
        // Bind to the native AdsObject to force authentication.
        Object obj = entry.NativeObject;
        DirectorySearcher search = new DirectorySearcher(entry);
        search.Filter = "(SAMAccountName=" + username + ")";
        search.PropertiesToLoad.Add("cn");
        SearchResult result = search.FindOne();
        if (null == result)
        {
            return false;
        }
        // Update the new path to the user in the directory
        _path = result.Path;
        _filterAttribute = (String)result.Properties["cn"][0];
    }
    catch (Exception ex)
    {
        //throw new Exception("Error authenticating user. " + ex.Message);
        return false;
    }
    return true;
}

pretty neat ha!

comments powered by Disqus