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

1
2
3
4
5
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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