Implement Active Directory Authentication in ASP.NET MVC 5

http://www.schiffhauer.com/mvc-5-and-active-directory-authentication/.

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.cs file 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.config file to include these elements.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
      <authentication mode="Forms">
          <forms name=".ADAuthCookie" loginUrl="~/Account/Login" timeout="45" slidingExpiration="false" protection="All" />
      </authentication>
      <membership defaultProvider="ADMembershipProvider">
          <providers>
              <clear />
              <add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" />
          </providers>
      </membership>
  </system.web>
  <connectionStrings>
      <add name="ADConnectionString" connectionString="LDAP://primary.mydomain.local:389/DC=MyDomain,DC=Local" />
  </connectionStrings>
</configuration>

It may take a few steps to get your LDAP connection string:

  1. 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.
  2. Open a command prompt and enter >dsquery server

    Let’s say the command returns the following:

    “CN=PRIMARY,CN=Servers,CN=Default-First-Site-Name,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’sprimary.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’s DC=MyDomain,DC=Local.

    So the full connection string is LDAP://primary.mydomain.local:389/DC=MyDomain,DC=Local.

Users will log in using just their username without the domain. So the correct username is Chris, notMYDOMAIN\Chris.

Leave a comment