Saturday, June 7, 2014

Quick and Dirty Forms Auth to Test Something Else

Recently I needed to test how an Application Cache would operate, if at all, when resources where protected by ASP.NET forms authentication within a ASP.NET MVC application. I didn't need a full forms auth implementation, just something quick. I've done most of this before, but had nearly forgotten the details.

The Web.config:

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880">
        <credentials passwordFormat="Clear">
          <user name="admin" password="password"/>
        </credentials>
      </forms>
    </authentication>

The AccountController with the [Authorize] attribute:

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && FormsAuthentication.Authenticate(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, false);
                return RedirectToLocal(returnUrl);
            }
 
            ModelState.AddModelError("", "The user name or password provided is incorrect.");

            return View(model);
        }

        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }

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

The LoginModel class:

    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; }
    }

The Login.cshtml file:

@model OfflinePartial.Models.LoginModel
@{
    ViewBag.Title = "Login";
}
<h2>Login</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <p>
        @Html.LabelFor(m => m.UserName)
        @Html.TextBoxFor(m => m.UserName)
        @Html.ValidationMessageFor(m => m.UserName)
    </p>
    <p>
        @Html.LabelFor(m => m.Password)
        @Html.PasswordFor(m => m.Password)
        @Html.ValidationMessageFor(m => m.Password)
    </p>
    <p><input type="submit" value="Log in" /></p>
}

No comments: