-
Notifications
You must be signed in to change notification settings - Fork 0
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();
}
}- 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