In this article, we will learn How to implement Cookie Authentication in ASP.NET Core without using Identity. I will try to cover every step so that beginners can easily understand.
In AccountController, the Login action method receives the returnurl as a parameter to which the user needs to be redirected after the successful authentication. Below is the Login.cshtml code used in the example.
@model
CookieAuthentication.Models.LoginModel
@{
ViewData["Title"] = "Login";
Layout = "~/Views/Shared/_Layout.cshtml"; }
<h2>Login</h2>
<hr /> <div class="row">
<div class="col-md-4"> <form asp-action="Login"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> @if (!string.IsNullOrEmpty(ViewBag.Message)) { <span class="text-danger"> @ViewBag.Message </span> } @Html.HiddenFor(x => x.ReturnUrl) <div class="form-group"> <label asp-for="UserName" class="control-label"></label> <input asp-for="UserName" class="form-control" /> <span asp-validation-for="UserName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Password" class="control-label"></label> <input asp-for="Password" class="form-control" /> <span asp-validation-for="Password" class="text-danger"></span> </div> <div class="form-group"> <div class="checkbox"> <label> <input asp-for="RememberLogin" /> @Html.DisplayNameFor(model
=> model.RememberLogin) </label> </div> </div> <div class="form-group"> <input type="submit" value="Login" class="btn
btn-default" /> </div> </form>
</div> </div> |
public class LoginModel { [Required] [Display(Name ="Username")] public string UserName { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } public bool
RememberLogin { get; set; } public string ReturnUrl { get; set; }
} |
public class AccountController : Controller { //Sample
Users Data, it can be fetched with the use of any ORM public List<UserModel> users = null; public AccountController() { users = new List<UserModel>(); users.Add(new UserModel() { UserId = 1,
Username = "Anoop", Password = "123", Role = "Admin" }); users.Add(new UserModel() { UserId = 2,
Username = "Other", Password = "123", Role = "User" }); }
public IActionResult Login(string ReturnUrl = "/") { LoginModel objLoginModel = new LoginModel(); objLoginModel.ReturnUrl =
ReturnUrl; return View(objLoginModel); } [HttpPost] public async
Task<IActionResult> Login(LoginModel objLoginModel) { if (ModelState.IsValid) { var user = users.Where(x =>
x.Username == objLoginModel.UserName && x.Password ==
objLoginModel.Password).FirstOrDefault(); if (user == null) { //Add logic here to display some message to user ViewBag.Message = "Invalid Credential"; return View(objLoginModel); } else { //A claim is a statement about a subject by an issuer and //represent attributes of the subject that are useful in the
context of authentication and authorization operations. var claims = new List<Claim>() { new
Claim(ClaimTypes.NameIdentifier,Convert.ToString(user.UserId)),
new
Claim(ClaimTypes.Name,user.Username), new Claim(ClaimTypes.Role,user.Role), new Claim("FavoriteDrink","Tea") }; //Initialize a new instance of the ClaimsIdentity with the
claims and authentication scheme var identity = new ClaimsIdentity(claims,
CookieAuthenticationDefaults.AuthenticationScheme); //Initialize a new instance of the ClaimsPrincipal with
ClaimsIdentity
var principal = new ClaimsPrincipal(identity); //SignInAsync is a Extension method for Sign in a principal for
the specified scheme. await
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties() {
IsPersistent = objLoginModel.RememberLogin });
return
LocalRedirect(objLoginModel.ReturnUrl); } } return View(objLoginModel); }
public async
Task<IActionResult> LogOut() { //SignOutAsync
is Extension method for SignOut await
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); //Redirect
to home page return LocalRedirect("/"); } } |
public async
Task<IActionResult> LogOut() { //SignOutAsync
is Extension method for SignOut await
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); //Redirect
to home page return LocalRedirect("/"); } |
I hope this article helped you in implementing Cookie Authentication in ASP.
0 comments:
Post a Comment