views:

1117

answers:

3

I would like to have a clean C# class that authenticates from Active Directory.

It should be pretty simple, it just has to ask for credentials and check if it matches what AD is expecting.

I am responsible for a number of C# applications, and I would like all of them to use the same class.

Could someone please provide a clean code sample of such a class? It should have good error handling, be well commented, and specifically ask for credentials rather than try to read if a user is already logged in to AD for another application. (This is a security requirement because some applications are used in areas with shared computers: People with multiple roles and different permission levels may use the same computer and forget to log out between sessions)

+1  A: 

There's some reason you can't use Windows integrated authentication, and not bother users with entering their names and passwords? That's simultaneously the most usable and secure solution when possible.

Pontus Gagge
This is a security requirement because some applications are used in areas with shared computers: People with multiple roles and different permission levels may use the same computer and forget to log out between sessions
Kaiser Advisor
+5  A: 

http://support.microsoft.com/kb/316748

public bool IsAuthenticated(String domain, String username, String pwd)
{
  String domainAndUsername = domain + "\\" + username;
  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 true;
 }
Bob
+1  A: 

Admittedly I have no experience programming against AD, but the link below seems it might address your problem.

http://www.codeproject.com/KB/system/everythingInAD.aspx#35

JTA