2009-06-12 57 views
5

是否有活動目錄助手類可用的地方?在我重新發明輪子之前檢查一下。活動目錄助手類

我需要在AD中

  1. 驗證用戶。

  2. 獲取hhis /她的成員角色。

感謝

回答

10

在.NET 3.5中,你想在System.DirectoryServices.AccountManagement看看。對於較早的版本,System.DirectoryServices版本具有您所需要的版本,但它的工作稍微多一點。

using (var context = new PrincipalContext(ContextType.Domain)) 
{ 
     var valid = context.ValidateCredentials(username, password); 
     using (var user = UserPrincipal.FindByIdentity(context, 
                 IdentityType.SamAccountName, 
                 username)) 
     { 
      var groups = user.GetAuthorizationGroups(); 
     } 
} 
+0

我正在開發一臺筆記本電腦,而不是域的一部分。我可以將此類請求傳遞給AD嗎? – 2009-06-12 00:40:07

3

這裏是我一直在使用一些示例代碼:

using System.DirectoryServices; 

public static string GetProperty(SearchResult searchResult, 
    string PropertyName) 
{ 
    if (searchResult.Properties.Contains(PropertyName)) 
     return searchResult.Properties[PropertyName][0].ToString(); 
    else 
     return string.Empty; 
} 

public MyCustomADRecord Login(string UserName, string Password) 
{ 
    string adPath = "LDAP://www.YourCompany.com/DC=YourCompany,DC=Com"; 

    DirectorySearcher mySearcher; 
    SearchResult resEnt; 

    DirectoryEntry de = new DirectoryEntry(adPath, UserName, Password, 
     AuthenticationTypes.Secure); 
    mySearcher = new DirectorySearcher(de); 

    string adFilter = "(sAMAccountName=" + UserName + ")"; 
    mySearcher.Filter = adFilter; 

    resEnt = mySearcher.FindOne(); 


    return new MyCustomADRecord() 
    { 
     UserName = GetProperty(resEnt, "sAMAccountName"), 
     GUID = resEnt.GetDirectoryEntry().NativeGuid.ToString(), 
     DisplayName = GetProperty(resEnt, "displayName"), 
     FirstName = GetProperty(resEnt, "givenName"), 
     MiddleName = GetProperty(resEnt, "initials"), 
     LastName = GetProperty(resEnt, "sn"), 
     Company = GetProperty(resEnt, "company"), 
     JobTitle = GetProperty(resEnt, "title"), 
     Email = GetProperty(resEnt, "mail"), 
     Phone = GetProperty(resEnt, "telephoneNumber"), 
     ExtensionAttribute1 = GetProperty(resEnt, "extensionAttribute1") 
    }; 
}