简体   繁体   中英

Generic Authentication Call to Active Directory in C#

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)

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;
 }

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM