简体   繁体   English

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

[英]Generic Authentication Call to Active Directory in C#

I would like to have a clean C# class that authenticates from Active Directory. 我想拥有一个从Active Directory进行身份验证的干净C#类。

It should be pretty simple, it just has to ask for credentials and check if it matches what AD is expecting. 它应该非常简单,只需询问凭据并检查其是否符合AD的预期。

I am responsible for a number of C# applications, and I would like all of them to use the same class. 我负责许多C#应用程序,我希望它们全部使用同一类。

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. 它应具有良好的错误处理能力,并具有良好的注释,尤其应要求提供凭据,而不要尝试读取用户是否已针对另一个应用程序登录到AD。 (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 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. 诚然,我没有针对AD进行编程的经验,但是下面的链接似乎可以解决您的问题。

http://www.codeproject.com/KB/system/everythingInAD.aspx#35 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? 出于某些原因,您不能使用Windows集成身份验证 ,并且不打扰用户输入用户名和密码? That's simultaneously the most usable and secure solution when possible. 在可能的情况下,这同时也是最有用和最安全的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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