Saturday, March 7, 2020

Create a simple Login using CookieAuthentication in ASP.NET Core

I am using Core 3.1

1) Configure Services in the Startup.cs

public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o => o.LoginPath = new PathString("/Home/Login"));
}

2) Add Configuration in the Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
}

3) Create a LogIn action method in the Controller

Here the user login information is received through a ViewModel

[HttpPost]
public ActionResult Login(LoginViewModel user)
{
if (ModelState.IsValid)
{
if (!string.IsNullOrEmpty(user.UserName) && !string.IsNullOrEmpty(user.Password))
{
var userId = _configuration.administrator.UserName;
var userPassword = _configuration.administrator.Password;

if (user.UserName == userId && user.Password == userPassword)
{
var claims = new[] { new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.Role, "Administrator") };

var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity));

return RedirectToAction("Index", "MyBusinessController");
}
else
{
TempData["LogInMessage"] = "LogIn failed. Incorrect username or password";
return RedirectToAction("Login");
}
}
}
return View(user);
}

4) Display the Logged in user probably in the _Layout.cshtml

                    @if (Context.User.Identities.Any(i => i.IsAuthenticated))
                    {
                        <div class="nnav navbar-nav" style="padding:10px 15px;float: right;text-align: left;color:#9d9d9d;padding-top: 15px;">
                        Welcome @Context.User.Identity.Name
                                    @Html.ActionLink("(Logout)", "Logout", "Home")
                        </div>
                    }

5) Logout action method
[Authorize]
public ActionResult Logout()
{
HttpContext.SignOutAsync(
CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login");
}

No comments:

Post a Comment