C#中的通用身份验证调用Active Directory

Kai*_*sor 0 c# authentication active-directory

我想有一个干净的C#类,可以从Active Directory进行身份验证.

它应该非常简单,它只需要请求凭据并检查它是否与AD期望的匹配.

我负责许多C#应用程序,我希望所有这些应用程序都使用相同的类.

有人可以提供这样一个类的干净代码样本吗?它应该具有良好的错误处理,得到很好的评论,并且特别要求提供凭据而不是尝试读取用户是否已经登录到另一个应用程序的AD.(这是安全要求,因为某些应用程序用于具有共享计算机的区域:具有多个角色和不同权限级别的人员可能使用同一台计算机而忘记在会话之间注销)

Bob*_*Bob 7

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;
 }
Run Code Online (Sandbox Code Playgroud)