Este es un complemento al tema de directorio activo, permite hacer validaciones de cuentas de usuario vs el directorio activo.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security; using System.Security.Principal; using System.DirectoryServices; using System.DirectoryServices.ActiveDirectory; using System.DirectoryServices.AccountManagement; namespace F.Net.ActiveDirectory { /// <summary> /// /// </summary> public class Validations { //srvr = ldap server, e.g. LDAP://domain.com //usr = user name //pwd = user password public static AuthenticationResult IsAuthenticated(string srvr, string usr, string pwd) { AuthenticationResult authenticated =new AuthenticationResult (); try { DirectoryEntry entry = new DirectoryEntry(srvr, usr, pwd); object nativeObject = entry.NativeObject; authenticated.IsAuthenticated = true ; authenticated.NonAuthenticatedReason = string.Empty ; } catch (DirectoryServicesCOMException cex) { authenticated.IsAuthenticated = false; authenticated.NonAuthenticatedReason = cex.ExtendedErrorMessage; //not authenticated; reason why is in cex } catch (Exception ex) { authenticated.IsAuthenticated = false; authenticated.NonAuthenticatedReason = "[Unhandled Error]"+ ex.Message; //not authenticated due to some other exception [this is optional] } return authenticated; } /// <summary> /// /// </summary> /// <param name="domain"></param> /// <param name="user"></param> /// <param name="password"></param> /// <returns></returns> public static AuthenticationResult ValidateCredentials(string domain, string user, string password) { AuthenticationResult isValid = new AuthenticationResult (); try { PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain); // validate the credentials isValid.IsAuthenticated = pc.ValidateCredentials(user, password); isValid.NonAuthenticatedReason = string.Empty; } catch (Exception ex) { isValid.IsAuthenticated = false; isValid.NonAuthenticatedReason = ex.Message; } return isValid; } /// <summary> /// /// </summary> /// <param name="path"></param> /// <param name="accountId"></param> /// <param name="password"></param> /// <returns></returns> public static bool IsAValidADUser(string path,string accountId,string password){ bool bSucceeded = false; DirectoryEntry adsEntry = new DirectoryEntry(path, accountId, password); DirectorySearcher adsSearcher = new DirectorySearcher( adsEntry ); adsSearcher.Filter = "(sAMAccountName=" + accountId + ")"; try { SearchResult adsSearchResult = adsSearcher.FindOne(); bSucceeded = true; adsEntry.Close(); } catch { // Failed to authenticate. Most likely it is caused by unknown user // id or bad strPassword. bSucceeded = false; adsEntry.Close(); } return bSucceeded; } } }