2009-04-22 67 views
0

我想有一个干净的C#类,从Active Directory进行身份验证。通用身份验证呼叫到C#中的Active Directory

它应该很简单,它只是要求凭据,并检查它是否符合AD的期望。

我负责一些C#应用程序,我希望他们都使用相同的类。

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

回答

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

有一些原因导致您无法使用Windows integrated authentication,而不会打扰用户输入他们的名字和密码?如果可能的话,这同时也是最有用和最安全的解决方案

+1

这是一个安全的要求,因为一些应用领域中使用共享计算机:拥有多重角色和不同权限级别的人可能使用同一台计算机,却忘了会话之间注销 – 2009-04-22 20:24:17

相关问题