User614698185 posted
Hi nazlin,
Firstly, install NuGet packages about Microsoft.Owin.Security.Cookies. This is the package that actually enables cookie based authentication.
Then, add the POST action (POST /auth/login) that validates the provided credentials and logs the user in:
[HttpPost]
public ActionResult LogIn(LogInModel model)
{
if (!ModelState.IsValid)
{
return View();
}
// Don't do this in production!
if (model.Email == "admin@admin.com" && model.Password == "password")
{
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, "Ben"),
new Claim(ClaimTypes.Email, "a@b.com"),
new Claim(ClaimTypes.Country, "England")
},
"ApplicationCookie");
var ctx = Request.GetOwinContext();
var authManager = ctx.Authentication;
authManager.SignIn(identity);
return Redirect(GetRedirectUrl(model.ReturnUrl));
}
// user authN failed
ModelState.AddModelError("", "Invalid email or password");
return View();
}
private string GetRedirectUrl(string returnUrl)
{
if (string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
{
return Url.Action("index", "home");
}
return returnUrl;
}
Logging Out: Add the following action to AuthController:
public ActionResult LogOut()
{
var ctx = Request.GetOwinContext();
var authManager = ctx.Authentication;
authManager.SignOut("ApplicationCookie");
return RedirectToAction("index", "home");
}
For more information, please refer to the following documents:
http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-1
http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-2
Best Regards,
Candice Zhou