2009-06-12 3 views
5

Esiste una classe helper per Active Directory disponibile da qualche parte? Sto solo controllando prima di re-inventare la ruota.Classe helper Active Directory

ho bisogno di

  1. Convalida un utente in AD.

  2. Ottieni i suoi ruoli membri.

Grazie

risposta

10

In .NET 3.5, si vuole guardare in System.DirectoryServices.AccountManagement. Per prima cosa, le versioni System.DirectoryServices hanno quello di cui hai bisogno, ma è un po 'più di lavoro.

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

Sto sviluppando su un laptop non appartenente al dominio. Posso passare tale richiesta ad AD? –

+2

Se gli utenti sono locali sulla macchina, è possibile utilizzare ContextType.Machine anziché ContextType.Domain per focalizzare le query sull'archivio autorizzazioni locale. – tvanfosson

3

Ecco qualche esempio di codice che ho utilizzato:

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") 
    }; 
} 
+0

Apprezzo che tu abbia condiviso questo. –