What are the high level steps to authenticate users of an ASP.NET MVC application against Active Directory?
I presume something like:
Here's a solution from the tutorial Chris Schiffhauer - Implement Active Directory Authentication in ASP.NET MVC 5:
You can secure your MVC web application on an Active Directory network by authenticating users directly against their domain credentials.
STEP 1: ACCOUNTCONTROLLER.CS
Replace your
AccountController.csfile with the following:using System.Web.Mvc; using System.Web.Security; using MvcApplication.Models; public class AccountController : Controller { public ActionResult Login() { return this.View(); } [HttpPost] public ActionResult Login(LoginModel model, string returnUrl) { if (!this.ModelState.IsValid) { return this.View(model); } if (Membership.ValidateUser(model.UserName, model.Password)) { FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); if (this.Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return this.Redirect(returnUrl); } return this.RedirectToAction("Index", "Home"); } this.ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect."); return this.View(model); } public ActionResult LogOff() { FormsAuthentication.SignOut(); return this.RedirectToAction("Index", "Home"); } }STEP 2: ACCOUNTVIEWMODELS.CS
Update your
AccountViewModels.cs(or whatever your Account model class is named) to contain only this LoginModel class:using System.ComponentModel.DataAnnotations; public class LoginModel { [Required] [Display(Name = "User name")] public string UserName { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } }STEP 3: WEB.CONFIG
Finally, update your
Web.configfile to include these elements.It may take a few steps to get your LDAP connection string:
Install Remote Server Administration Tools for Windows 7. Be sure the follow the post-installation instructions to add the feature to Windows via the control panel.
Open a command prompt and enter
>dsquery serverLet’s say the command returns the following:
CN=PRIMARY,CN=Servers,CN=DefaultFirstName,CN=Sites,CN=Configuration,DC=MyDomain,DC=Local
The server name is composed of the first CN value, and the two last DC values, separated by dots. So it's
primary.mydomain.local.The port is 389.
The portion of the connection string after the port and forward slash is the portion of the result beginning with the first
"DC". So it'sDC=MyDomain,DC=Local.So the full connection string is
LDAP://primary.mydomain.local:389/DC=MyDomain,DC=Local.Users will login using just their username without the domain. So the correct username is Chris, not MYDOMAIN\Chris.