.NET C#: Authenticate Against Active Directory (AD)

1/6/2015 4:26:46 PM

The following is used to authenticate a user against Active Directory (AD). This can be combined with forms authentication to set the auth cookie.

//requires a reference to System.DirectoryServices.AccountManagement

string domain = "mydomain";
using (System.DirectoryServices.AccountManagement.PrincipalContext pc = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, domain))
{
	// validate the credentials
	if (pc.ValidateCredentials(model.Username, model.Password))
	{
		//do something
		
		//set auth cookie
		System.Web.Security.FormsAuthentication.SetAuthCookie(model.Username, false);
	}
}