It is not that simple 🙂
-
In the Startup.cs, configure method.
app.UseCookieAuthentication(options => { options.AutomaticAuthenticate = true; options.AutomaticChallenge = true; options.LoginPath = "/Home/Login"; });
-
Add Authorize attribute to protect the resources you want to secure.
[Authorize] public IActionResult Index() { return View(); }
-
In the Home Controller, Login Post action method, write the following method.
var username = Configuration["username"]; var password = Configuration["password"]; if (authUser.Username == username && authUser.Password == password) { var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); HttpContext.Authentication.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); return Redirect("~/Home/Index"); } else { ModelState.AddModelError("","Login failed. Please check Username and/or password"); }
Here is the github repo for your reference : https://github.com/anuraj/CookieAuthMVCSample