Form Wizard Pro And JQuery Word Count Revisited, Yet Again
November 23, 2016
Tracking E-mail Opens
November 24, 2016

Active Directory Authentication in ASP.NET MVC 5

In case it’s useful to others, here’s some sample code in order to get LDAP working with MVC 5 at Colorado State University.  When deploying remotely, please be sure to switch to using SSL. Web.Config <connectionStrings> <add name="PartySmart_AD" connectionString="LDAP://colostate.edu:389/DC=colostate,DC=edu"/> </connectionStrings> <location path="admin"> <system.web> <authorization> <allow users="sgeisert" /> <deny users="*" /> </authorization> </system.web> </location> <system.web> <!-- [...]

In case it’s useful to others, here’s some sample code in order to get LDAP working with MVC 5 at Colorado State University.  When deploying remotely, please be sure to switch to using SSL.

Web.Config

  <connectionStrings>

          <add name="PartySmart_AD" connectionString="LDAP://colostate.edu:389/DC=colostate,DC=edu"/>

      </connectionStrings>

      <location path="admin">

          <system.web>

              <authorization>

                  <allow users="sgeisert" />

                  <deny users="*" />

              </authorization>

          </system.web>

      </location>

      <system.web>

          <!-- It is STRONGLY recommended that you visit http://www.developerfusion.com/tools/generatemachinekey/ and generate your own key below -->

          <machineKey

            validationKey="xxx"

            decryptionKey="xxx"

            validation="SHA1" decryption="AES"

          />

          <authentication mode="Forms">

              <forms loginUrl="~/Account/Login" timeout="45" slidingExpiration="true" protection="All" />

          </authentication>

          <membership defaultProvider="PartySmart_ADProvider">

              <providers>

                  <clear/>

                  <add name="PartySmart_ADProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="PartySmart_AD" attributeMapUsername="sAMAccountName" />

              </providers>

          </membership>

          <compilation debug="true" targetFramework="4.5" />

          <httpRuntime targetFramework="4.5" />

      </system.web>

      <system.webServer>

          <modules runAllManagedModulesForAllRequests="true">

              <remove name="FormsAuthentication" />

              <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />

          </modules>

      </system.webServer>

AccountController.cs

  using System.Web.Mvc;

  using System.Web.Security;

  using OCL_PartySmart.Models;

  namespace OCL_PartySmart.Controllers

  {

      [Authorize]

      public class AccountController : Controller

      {

          //

          // GET: /Account/Login

          [AllowAnonymous]

          public ActionResult Login(string returnUrl)

          {

              ViewBag.ReturnUrl = returnUrl;

              return View();

          }

          //

          // POST: /Account/Login

          [HttpPost]

          [AllowAnonymous]

          [ValidateAntiForgeryToken]

          public ActionResult Login(LoginViewModel model, string returnUrl)

          {

              if (ModelState.IsValid)

              {

                  if (Membership.ValidateUser(model.UserName, model.Password))

                  {

                      FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

                      if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")

                          && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\"))

                      {

                          return Redirect(returnUrl);

                      }

                      else

                      {

                          return RedirectToAction("Index", "Home");

                      }

                  }

                  else

                  {

                      ModelState.AddModelError("", "The user name or password provided is incorrect");

                  }

              }

              // if we got this far, something failed, redisplay form

              return View(model);

          }

          //

          // POST: /Account/LogOff

          [HttpPost]

          [ValidateAntiForgeryToken]

          public ActionResult LogOff()

          {

              FormsAuthentication.SignOut();

              return RedirectToAction("Index", "Home");

          }

  }

  }

AccountViewModels.cs

  public class LoginViewModel

      {

          [Required]

          [Display(Name = "User name")]

          public string UserName { get; set; }

          [Required]

          [DataType(DataType.Password)]

          public string Password { get; set; }

          [Display(Name = "Remember me?")]

          public bool RememberMe { get; set; }

      }

 

Login.cshtml (Razor syntax)

  @using OCL_PartySmart.Models

  @model LoginViewModel

  @{

      ViewBag.Title = "Log in";

  }

  <h2>@ViewBag.Title.</h2>

  <div class="row">

      <div class="col-md-8">

          <section id="loginForm">

              @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))

              {

                  @Html.AntiForgeryToken()

                  <h4>Use a local account to log in.</h4>

                  <hr />

                  @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                  <div class="form-group">

                      @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })

                      <div class="col-md-10">

                          @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })

                          @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })

                      </div>

                  </div>

                  <div class="form-group">

                      @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })

                      <div class="col-md-10">

                          @Html.PasswordFor(m => m.Password, new { @class = "form-control" })

                          @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })

                      </div>

                  </div>

                  <div class="form-group">

                      <div class="col-md-offset-2 col-md-10">

                          <div class="checkbox">

                              @Html.CheckBoxFor(m => m.RememberMe)

                              @Html.LabelFor(m => m.RememberMe)

                          </div>

                      </div>

                  </div>

                  <div class="form-group">

                      <div class="col-md-offset-2 col-md-10">

                          <input type="submit" value="Log in" class="btn btn-default" />

                      </div>

                  </div>

              }

          </section>

      </div>

  </div>

  @section Scripts {

      @Scripts.Render("~/bundles/jqueryval")

  }