Skip to content

Authentication in ASP.NET Core MVC

Problem definition: Authentication is the process of checking whether a user is who they claim to be. In applications, registered users log in with a username and password, and only if these are validated against the database can they access the application. Users who are not logged in should be redirected to the login page.

In the image below you can see a login page with UserName, Password and a Remember Me checkbox. When the user clicks the Login button, the username and password are validated against the database. Remember Me is used for cookie authentication.

Login page with UserName, Password and Remember Me fields
Home page with a Log Out link after successful login

When the user clicks Log Out on the home page, they are logged out of the application and redirected back to the login page. To log in again, they need to enter their username and password.

Implementation: To implement authentication, follow the steps below.

  • Create a model class for users.
  • Create a controller named UserAccess.
  • Create an action method named Login inside the controller.
  • Create a Login view to enter the username and password.
  • Add a list item in the layout page for the Log Out button.
  • Add this User model class to the DbContext class and then run the migration commands.
  • Add the view for the Login action method.
  • Create an action method named LogOut in HomeController to log out of the application.
  • Add the connection string to the appsettings.json file.
  • Add the middleware and services for authentication in the Program.cs file.
  • Install the required packages from the NuGet Package Manager.
  • Add the references to the Identity classes in the controllers.

The image below shows the required packages. Install them from the NuGet Package Manager with the latest compatible version.

Required NuGet packages for cookie authentication and Entity Framework Core

In the implementation phase, we create a model class for users. Below is the code for the User model class.

public class User

  {

      [Key]

      public int UserId { get; set; }

      [Required]

      public string FulltName { get; set; }



      [Required]

      public string UserName { get; set; }

      [Required]

      public string Password { get; set; }

      public bool RememberMe { get; set; }

  }

Add the connection string to the appsettings.json file, as shown in the image below, where CorePracticeDB is the name of the database we want to create for our application. Here we use a local server; you can change it to your server name or IP address.

CorePracticeDB connection string in appsettings.json

Now create a DbContext class named ApplicationDBContext and add the DbSet below. It generates the table in the database when you run the migration commands, as shown in the images below.

public class ApplicationDBContext :DbContext

   {

       public ApplicationDBContext(DbContextOptions options) :base(options)

       {



       }

       public DbSet<User> Users { get; set; }

   }
Running Add-Migration in Package Manager Console
Add-Migration FirstMigration and Update-Database commands in Package Manager Console

After running the migration commands, you can see the Migrations folder in Solution Explorer, with a migration class containing auto-generated code that creates the database tables from the model classes, because we are using code-first migrations. Below is an image of the Migrations folder and the migration class.

Migrations folder with the auto-generated migration class

Add the code below to the Program.cs file for the middleware and services.

Cookie authentication services and middleware in Program.cs

Now create a controller named UserAccess and write the action methods below in it. Login() validates the user against the database.
LogOut(), written in HomeController, logs the user out of the application and redirects them to the login page.
First, add the references below to the controller.

using System.Security.Claims;

using Microsoft.AspNetCore.Authentication;

using Microsoft.AspNetCore.Authentication.Cookies;

using Microsoft.EntityFrameworkCore;

Now add the code below to the controller for authentication.

public class UserAccessController : Controller

   {

       private readonly ApplicationDBContext db;

       public UserAccessController(ApplicationDBContext _db)

       {

           db = _db;

       }

       [HttpGet]

       public IActionResult Login()

       {

           ClaimsPrincipal claimUser = HttpContext.User;

           if (claimUser.Identity.IsAuthenticated)

               return RedirectToAction("Index", "Home");

           return View();

       }

       [HttpPost]

       public async Task<IActionResult> Login(User user)

       {

           var userData=db.Users.Where(u => u.UserName == user.UserName && u.Password==user.Password).FirstOrDefault();

           if(userData==null)

           {

               ViewData["MSG"] = "Invalid User.Password";

               return View();

           }

           List<Claim> claims = new List<Claim>()

           {

               new Claim(ClaimTypes.NameIdentifier, user.UserName),

               new Claim(ClaimTypes.Name,userData.FulltName)

           };

           ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);

           AuthenticationProperties properties = new AuthenticationProperties()

           {

               AllowRefresh = true,

           IsPersistent = user.RememberMe

           };

           await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,

               new ClaimsPrincipal(claimsIdentity), properties);

           return RedirectToAction("Index","Home");

       }

   }

Now create a view for the Login action method, as shown below. The login view is split across two images only to keep the code readable.

Razor login view code (part 1)
Razor login view code (part 2)

Add the references below to HomeController for the Identity and Claims classes.

using Microsoft.AspNetCore.Authentication;

using Microsoft.AspNetCore.Authentication.Cookies;

using Microsoft.AspNetCore.Authorization;

Now create a LogOut action method in HomeController and write the code below.

public async Task<IActionResult> LogOut()

       {

           await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

           return RedirectToAction("Login","UserAccess");

       }

Decorate HomeController with the [Authorize] attribute, as shown in the image below.

HomeController decorated with the [Authorize] attribute

Now run the application. Authentication works, and users can access the application only after logging in.