Authentication in ASP.NET Core MVC

Problem Defination :- Authentication is the process in which we check the user is Authenticated or not. In Applications registered users login with UserName and Password,if UserName and Password is validated from the Database then only users can access the application. Without login application should redirect users on login page.

In the below Image you can see a login page with UserName,Password and Remember Me checkbox.On click of login button UserName and Password is validated into the database and remember me is used for Cookies Authentication.

Image is not available
Image is not available

When we Clicked on Log Out in Application Home Page then user will logged out from the application and redirected back to login page. If user wants to login again then they need to login by UserName and Password.

Implementation :- To implement Authentication functionality firstly we have to follow below steps

  • Create a Model Class for Users.
  • Create a Controller named it UserAccess.
  • Create a Action Method named it Login inside the controller.
  • Create one Login View to enter username and password.
  • Add a list item in Layout page for Log Out Button.
  • Add these User model class into the DbContext class and then execute the migration commands.
  • Add the View for Login Action Method.
  • Create a Action Method in Home Controller for Log Out from application and named it as Log Out.
  • Add the Connection String in AppSettings.Json file.
  • Add the Middileware and services for Authentication in program.cs file.
  • Install required Packages for Nuget Package Manager.
  • Add the references into Controllers for Identity Classes.

In Below Image required packages are shown and you can install it from nuget package manager with latest/compatible version.

Image is not available

In The implemetation phase we will create one model class which is used for Users. Below is the code for User Model Class 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 into the appSettings.JSON file as shown in below image in which CorePracticeDB is the name of the database we want to create for our application.Here we have used local server you can change it by your server name or IP address.

Image is not available

Now create a DBContext class and named it as ApplicationDBContext and add the below one DBSet into this class that will generate the table into the database when you run the migration commands as shown in below images.

                
 public class ApplicationDBContext :DbContext
    {
        public ApplicationDBContext(DbContextOptions options) :base(options)
        {

        }
        public DbSet Users { get; set; }
    }
               
                        
Image is not available
Image is not available

After successfully executed the migration commands now you are able to see migration folder in solution explorere and a migration class which has autogenerated code used for generating the tables in database using the model classes as we are using the code first migration.Below is the image of migration folder and migration class.

Image is not available

Add the Below Code into Program.cs file for Middileware and services.

Image is not available

Now Create the Controller with named UserAccess and write the below Action Methods into it. Login() is the method in which we are using for validating the user from database.
Log out() is the method wrriten in Home Controller is used for log out the user from the application and redirected it to the login page.
Firstly add the below references into the controller.

                
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;
                            
                        

Now Add the Below code into the controller for Authentication Purpose.

                
 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 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 claims = new List()
            {
                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 in fig and concatenate the below views.We have attached the login view in two different images only due to visibility of code.

Image is not available
Image is not available

Add below references in Home Controller for Identity and Claims Classes.

                
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
                            
                        

Now create a LogOut Action Method in Home Controller and write the below code.

                
 public async Task LogOut()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Login","UserAccess");
        }
                            
                        

Decorate Home Controller with [Authorize] Keyword like below image.

Image is not available

Now run the application authentication will work and you will be able to logged in the application only after authentication the User.


Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.