Skip to content

Cookie Authentication

txgz999 edited this page Jul 25, 2019 · 29 revisions

Cookie authentication is similar to forms authentication, but it can be used by OWIN applications. As an example, we create an ASP.NET web application with MVC template, then

  • install package Microsoft.Owin.Host.SystemWeb
  • install package Microsoft.Owin.Security.Cookies
  • create Startup.cs
public class Startup {
    public void Configuration(IAppBuilder app) {
        ConfigureOAuth(app);
    }
    public void ConfigureOAuth(IAppBuilder app) {
        app.UseCookieAuthentication(new CookieAuthenticationOptions {
            AuthenticationType = "AppCookie",
            LoginPath = new PathString("/Home/Login"),
        });
    }
}
  • create a login form, first create the action methods in the Home controller:
public class HomeController : Controller {
    [HttpGet]
    public ActionResult Login() {
        return View();
    }

    [HttpPost]
    public ActionResult Login(LoginModel model) {
        if (model.UserName == "test" && model.Password == "test") {
            var claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, model.UserName));
            var id = new ClaimsIdentity(claims, "AppCookie");
            var ctx = Request.GetOwinContext();
            var authenticationManager = ctx.Authentication;
            authenticationManager.SignIn(id);
            return RedirectToAction("Index", "Home");
        }
        return View(model);
    }

    [Authorize]
    public ActionResult Index() {
        return View();
    }
}

Notice that I have added the Authorize decorator to the Index page, so if the user has not logged in yet, the application would take the user to the Login page when he tries to access the home page.

  • and the corresponding view
<h2>Login</h2>
@using (Html.BeginForm("Login", "Home", FormMethod.Post)) {
    @Html.ValidationSummary(true)
  <fieldset>
    @Html.LabelFor(m => m.UserName):
    @Html.TextBoxFor(m => m.UserName)
    <br />
    @Html.LabelFor(m => m.Password):
    @Html.TextBoxFor(m => m.Password)
    <br />
    <input type="submit" value="Submit" />
  </fieldset>
}
  • LoginModel class is defined as
public class LoginModel {
    public string UserName { get; set; }
    public string Password { get; set; }
}
  • then we want to show the current login status by adding the following to _Layout.cshtml
    @User.Identity.Name

Notice that I hard code the AuthenticationType value. It can be any value, as long as the Startup class and the Login method use the same value. Some sample uses the value DefaultAuthenticationTypes.ApplicationCookie, which is the constant ApplicationCookie, but in order to use it we have to install the package Microsoft.AspNet.Identity.Core. That value determines the cookie name (.AspNet.<AuthenticationType>).

Clone this wiki locally