Scott Reynolds asks if there is a way to authenticate against AD without using a try/catch block to know if the user is valid. I didn't find a way but I'm okay with that as the following code I did for custom web service authentication *works*.
/// <summary>
/// Authenticates a user against Active Directory
/// </summary>
/// <param name="adPath">The path to the Active Directory provider to authenticate against.</param>
/// <param name="username">The username to authenticate with.</param>
/// <param name="pwd">The password used to authenticate the username with.</param>
/// <returns>An initialized IIdentity instance for the supplied user</returns>
internal static IIdentity AuthenticateUser(string adPath, string username, string pwd)
{
GenericIdentity identity = null;
DirectoryEntry entry = new DirectoryEntry(adPath, username, pwd);
try
{
// bind the native AdsObject to force authentication
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(userPrincipalName=" + username + ")";
search.PropertiesToLoad.Add("cn");
search.PropertiesToLoad.Add("distinguishedName");
SearchResult result = search.FindOne();
if(result == null)
{
throw new SoapException("Error authenticating user.",
SoapException.ClientFaultCode);
}
identity = new GenericIdentity(username, "LdapAuthentication");
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
return identity;
}
As my blog tagline says, *Pragmatic* Enthusiast - I am enthusiastic about technology but I'm also *pragmatic* ;)