Raymond Morphy
Raymond Morphy

Reputation: 2526

Active directory authentication

I'm using the code below to authenticate a user in Active Directory, but the password is sending in clear text. How can I hash my password and then send it to Active Directory?

DirectoryEntry entry = new DirectoryEntry(path, username, 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 true;

Upvotes: 7

Views: 2368

Answers (1)

marc_s
marc_s

Reputation: 755411

If you are using .NET 3.5, then I'd strongly recommend switching to using the System.DirectoryServices.AccountManagement namespace (read all about it: Managing Directory Security Principals in the .NET Framework 3.5).

Lots of things are a lot easier in S.DS.AM - like authenticating users:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
ctx.ValidateCredentials("test", "test", ContextOptions.SecureSocketLayer);

The only way to do this securely is by specifying the ContextOptions.SecureSocketLayer option to enforce using an SSL protected connection.

If you cannot move to .NET 3.5 and S.DS.AM, you need to check out the AuthenticationTypes that you can define in the fourth overloaded constructor of DirectoryEntry:

DirectoryEntry entry = 
     new DirectoryEntry(path, username, pwd, 
                        AuthenticationTypes.SecureSocketsLayer);

There's no other way to do this, I'm afraid - I don't think there's any way for you on the client-side to hash a password the same way Windwos Server / Active Directory do it, and pass in that hashed value...

Upvotes: 6

Related Questions