Authentication and Authorization (Claims, Roles and Policies)
Steps for Cookie-based Authentication
1. Using Claims
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using System.Security.Claims;[Authorize] public IActionResult Private() { return View(); }[HttpGet] public IActionResult Login(string ReturnUrl) { ViewBag.ReturnUrl = ReturnUrl; return View(); }[HttpPost] public IActionResult Login(string username, string password, string ReturnUrl) { if (username == "ram" && password == "ram") { List<Claim> claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, username)); claims.Add(new Claim(ClaimTypes.Name, username)); ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); ClaimsPrincipal principal = new ClaimsPrincipal(identity); HttpContext.SignInAsync(principal); return Redirect(ReturnUrl); } return View(); }@{ ViewData["Title"] ="Login"; } @{ string retUrl = ViewBag.ReturnUrl; } <form method="post" action="Login?ReturnUrl=@System.Net.WebUtility.UrlEncode(retUrl)" > <label>Username</label> <input type="text" name="username" /><br /> <label>Password</label> <input type="text" name="password" /><br /> <input type="submit" name="submit" value="login" /> </form>
// to add cookie authentication using Microsoft.AspNetCore.Authentication.Cookies; // adding authentication through cookie // after adding cookie, login path must be /Home/Login builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => options.LoginPath = "/Home/Login");
2. Using Roles
3. Using Policies
Last updated