Authentication and Authorization in ASP.NET
Steps to add Authentication and Authorization in ASP.NET Core
1. Using Username and Password only (no roles)
using Microsoft.AspNetCore.Authentication; // to add authentication using Microsoft.AspNetCore.Authentication.Cookies; // to add cookie using Microsoft.AspNetCore.Authorization; // to add authorization using System.Security.Claims; // to add claims -> claims are the authorization details[Authorize] public IActionResult Privacy() { return View(); }/** * This is the get method for login * It will take return url and send it to the view */ [HttpGet] public IActionResult Login(string ReturnUrl) { // take return url to view for this use ViewData ViewData["returnURL"] = ReturnUrl; return View(); }/** * This is the post method for login * It will take username and password and return to the return url */ [HttpPost] public IActionResult Login(string username, string password, string ReturnUrl) { if (username == "ram" && password == "ram") { // add authroization // claim: authorization detail // identity: which mechanism to be used for authorization:cookie // principal: who is authorized List<Claim> claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, username)); claims.Add(new Claim(ClaimTypes.Name, username)); // identity->claims ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); // principal->identity ClaimsPrincipal principal = new ClaimsPrincipal(identity); // executing->sign in HttpContext.SignInAsync(principal); //execute return Redirect(ReturnUrl); } return View(); }@* create login form and also extract return url *@ @{ ViewData["Title"] ="Login"; } @{ string retUrl = ViewData["returnURL"] as string; } <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
Last updated