Cookie Authentication In .NET Core 3.0

Introduction

 
Authentication is the process of determining or giving an individual access to system or user based on their identity. There are multiple options to do authentication in .net core. This article demonstrates how to add cookie base authentication in .net core 3.0.
 
With .net core 3.0, you can use cookie-based authentication out of box without adding new additional NuGet packages.
 
Prerequisites
  • Install .NET Core 3.0.0 or above SDK from here.
  • Install the latest version of Visual Studio 2019 Community Edition from here.

Steps for creating a web application 

 
Step 1
 
Go to Visual Studio 2019 then select Create new project option from option list.
 
Cookie Authentication In .NET Core 3.0
 
Step 2
 
After selecting that, a new window will open to select project template.
 
Step 3
 
Select “ASP.NET Core Web Application” and click on Next button. 
 
Cookie Authentication In .NET Core 3.0
 
Step 4
 
A new screen will open to configure your new project. Provide Project Name, Location, Solution Name as per your requirement. Press Create button.
 
Cookie Authentication In .NET Core 3.0
 
Step 5
 
After clicking on the Create button, a new screen will open to configure your project related information like which environment do you want create for web application? .Net Framework or .Net Core. Select .Net Core and ASP.NET Core Version from drop down list. Then, select web application (Model-View-Controller) option from list and press create button to create a project.
 
Cookie Authentication In .NET Core 3.0
 
Now our project will open with the basic structure of .net core environment. You can observe in the solution explorer that will have Controllers, Models and Views folders with “Startup.cs” and other files as well like below image.
 
Cookie Authentication In .NET Core 3.0
 
Step 6
 
Run your application to check if the created web application is running fine or not. By default, it will open a Home page (Index page of Home controller) of your project.
 
Integrate Cookie Authentication
  1. [Authorize] :- attribute helps to validate user to an access controller (User Information).
  2. Claim :- Contains user related information which will store into cookie.
  3. ClaimsIdentity :- Passes list of claims and AuthenticationTypes
  4. ClaimsPrincipal :-  Accept an array of ClaimsIdentity.
  5. SignInAsync:- Passes ClaimsPrinciple to it as paramater and finally this method will create a cookie into the browser.
Statup.cs file code changes
 
Open “Statup.cs” file and add AddAuthentication service into ConfigureServices method like below. Provide login path to login user to check/verify if user is valid or not.
  1. public void ConfigureServices(IServiceCollection services)  
  2.  {  
  3.             services.AddAuthentication("CookieAuthentication")  
  4.                  .AddCookie("CookieAuthentication", config =>  
  5.                  {  
  6.                      config.Cookie.Name = "UserLoginCookie";  
  7.                      config.LoginPath = "/Login/UserLogin";  
  8.                  });  
  9.   
  10.             services.AddControllersWithViews();  
  11.  }  
Add UseAuthentication and UseAuthorization extension method into Configure method of “Starup.cs”.
  • UseAuthentication - helps us to check “Who are you?”
  • UseAuthorization - helps to check “Are you allowed to access  information?”
Complete code in Startup.cs file,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Builder;  
  6. using Microsoft.AspNetCore.Hosting;  
  7. using Microsoft.AspNetCore.HttpsPolicy;  
  8. using Microsoft.Extensions.Configuration;  
  9. using Microsoft.Extensions.DependencyInjection;  
  10. using Microsoft.Extensions.Hosting;  
  11.   
  12. namespace CookieAuthenticationDemo  
  13. {  
  14.     public class Startup  
  15.     {  
  16.         public Startup(IConfiguration configuration)  
  17.         {  
  18.             Configuration = configuration;  
  19.         }  
  20.   
  21.         public IConfiguration Configuration { get; }  
  22.   
  23.         // This method gets called by the runtime. Use this method to add services to the container.  
  24.         public void ConfigureServices(IServiceCollection services)  
  25.         {  
  26.             services.AddAuthentication("CookieAuthentication")  
  27.                  .AddCookie("CookieAuthentication", config =>  
  28.                  {  
  29.                      config.Cookie.Name = "UserLoginCookie";  
  30.                      config.LoginPath = "/Login/UserLogin";  
  31.                  });  
  32.   
  33.             services.AddControllersWithViews();  
  34.         }  
  35.   
  36.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  37.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  38.         {  
  39.             if (env.IsDevelopment())  
  40.             {  
  41.                 app.UseDeveloperExceptionPage();  
  42.             }  
  43.             else  
  44.             {  
  45.                 app.UseExceptionHandler("/Home/Error");  
  46.                 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
  47.                 app.UseHsts();  
  48.             }  
  49.             app.UseHttpsRedirection();  
  50.             app.UseStaticFiles();  
  51.   
  52.             app.UseRouting();  
  53.   
  54.             // who are you?  
  55.             app.UseAuthentication();  
  56.   
  57.             // are you allowed?  
  58.             app.UseAuthorization();  
  59.   
  60.             app.UseEndpoints(endpoints =>  
  61.             {  
  62.                 endpoints.MapControllerRoute(  
  63.                     name: "default",  
  64.                     pattern: "{controller=Home}/{action=Index}/{id?}");  
  65.             });  
  66.         }  
  67.     }  
  68. }  
Add User.cs file into Model folder
 
Add new class into Models folder with name Users and put the below lines of code into it.
  1. using System.Collections.Generic;  
  2.   
  3. namespace CookieAuthenticationDemo.Models  
  4. {  
  5.     public class Users  
  6.     {  
  7.         public int Id { getset; }  
  8.         public string UserName { getset; }  
  9.         public string Name { getset; }  
  10.         public string EmailId { getset; }  
  11.         public string Password { getset; }  
  12.   
  13.         public IEnumerable<Users> GetUsers()  
  14.         {  
  15.             return new List<Users>() { new Users { Id = 101, UserName = "anet", Name = "Anet", EmailId = "anet@test.com", Password = "anet123" } };  
  16.         }  
  17.     }  
  18. }  

Update HomeController with new action method

 
HomeController is default controller created by Visual Studio while creating a new project. 
 
a) Add a new action method into HomeController to get list of users with Authorize attribute.
  1. using CookieAuthenticationDemo.Models;  
  2. using Microsoft.AspNetCore.Authorization;  
  3. using Microsoft.AspNetCore.Mvc;  
  4.   
  5. namespace CookieAuthenticationDemo.Controllers  
  6. {  
  7.     public class HomeController : Controller  
  8.     {  
  9.         public IActionResult Index()  
  10.         {  
  11.             return View();  
  12.         }  
  13.   
  14.         [Authorize]  
  15.         public ActionResult Users()  
  16.         {  
  17.             var uses = new Users();  
  18.             return View(uses.GetUsers());  
  19.         }  
  20.        
  21.     }  
  22. }  
b) Add view for users
  1. Go to Views folder and select Home folder
  2. Right click on the Home folder to select add option and select view.
  3. A window popup will open to add View.
  4. Provide view name as User, select Template as Empty, select use layout page and press Add button. A new Users.cshtml file will create into Home folder. Refer to the below image to add view.
Cookie Authentication In .NET Core 3.0
 
Put the below lines of code into it to show list of users
  1. @model IEnumerable<CookieAuthenticationDemo.Models.Users>    
  2.     
  3. @{    
  4.     ViewData["Title"] = "Users";    
  5. }    
  6.     
  7. <h1>Users</h1>    
  8. <table class="table">    
  9.     <thead>    
  10.         <tr>    
  11.             <th>    
  12.                 @Html.DisplayNameFor(model => model.Id)    
  13.             </th>    
  14.             <th>    
  15.                 @Html.DisplayNameFor(model => model.UserName)    
  16.             </th>    
  17.             <th>    
  18.                 @Html.DisplayNameFor(model => model.Name)    
  19.             </th>    
  20.             <th>    
  21.                 @Html.DisplayNameFor(model => model.EmailId)    
  22.             </th>    
  23.             <th></th>    
  24.         </tr>    
  25.     </thead>    
  26.     <tbody>    
  27. @foreach (var item in Model) {    
  28.         <tr>    
  29.             <td>    
  30.                 @Html.DisplayFor(modelItem => item.Id)    
  31.             </td>    
  32.             <td>    
  33.                 @Html.DisplayFor(modelItem => item.UserName)    
  34.             </td>    
  35.             <td>    
  36.                 @Html.DisplayFor(modelItem => item.Name)    
  37.             </td>    
  38.             <td>    
  39.                 @Html.DisplayFor(modelItem => item.EmailId)    
  40.             </td>    
  41.         </tr>    
  42. }    
  43.     </tbody>    
  44. </table>   
Add new controller with name Login
  • Right click on controllers folder
  • Select Add then select Controller and then select MVC empty controller and click on add button. 
  • Add controller with name Login as “LoginController”
  • Add below code into that controller
  1. using CookieAuthenticationDemo.Models;  
  2. using Microsoft.AspNetCore.Authentication;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Security.Claims;  
  7.   
  8. namespace CookieAuthenticationDemo.Controllers  
  9. {  
  10.     public class LoginController : Controller  
  11.     {  
  12.         [HttpGet]  
  13.         public ActionResult UserLogin()  
  14.         {  
  15.             return View();  
  16.         }  
  17.   
  18.         [HttpPost]  
  19.         public ActionResult UserLogin([Bind] Users user)  
  20.         {  
  21.             // username = anet  
  22.             var users = new Users();  
  23.             var allUsers = users.GetUsers().FirstOrDefault();  
  24.             if (users.GetUsers().Any(u => u.UserName == user.UserName ))  
  25.             {  
  26.                 var userClaims = new List<Claim>()  
  27.                 {  
  28.                 new Claim(ClaimTypes.Name, user.UserName),  
  29.                 new Claim(ClaimTypes.Email, "anet@test.com"),  
  30.                  };  
  31.   
  32.                 var grandmaIdentity = new ClaimsIdentity(userClaims, "User Identity");  
  33.   
  34.                 var userPrincipal = new ClaimsPrincipal(new[] { grandmaIdentity });  
  35.                 HttpContext.SignInAsync(userPrincipal);  
  36.   
  37.                 return RedirectToAction("Index""Home");  
  38.             }  
  39.   
  40.             return View(user);  
  41.         }  
  42.     }  
  43. }  
Add a UserLogin.cshtml(UserLogin view) page,
  • Add new folder into Views folder with name User.
  • Add UserLogin into User folder and add below lines of code into it to user login
Code for UserLogin.cshtml
  1. @model CookieAuthenticationDemo.Models.Users    
  2.     
  3. @{    
  4.     ViewData["Title"] = "User Login";    
  5. }    
  6.     
  7. <hr />    
  8. <div class="row">    
  9.     <div class="col-md-4">    
  10.         <form asp-action="UserLogin">    
  11.             <h2>User Login</h2>    
  12.             <div asp-validation-summary="ModelOnly" class="text-danger"></div>    
  13.             <div class="form-group">    
  14.                 <label asp-for="UserName" class="control-label"></label>    
  15.                 <input asp-for="UserName" class="form-control" />    
  16.                 <span asp-validation-for="UserName" class="text-danger"></span>    
  17.             </div>    
  18.             <div class="form-group">    
  19.                 <label asp-for="Password" class="control-label"></label>    
  20.                 <input type="password" asp-for="Password" class="form-control" />    
  21.                 <span asp-validation-for="Password" class="text-danger"></span>    
  22.             </div>    
  23.             <div class="form-group">    
  24.                 <input type="submit" value="Login" class="btn btn-default btn-primary" />    
  25.             </div>    
  26.         </form>    
  27.     </div>    
  28. </div>    
Update _Layout.cshtml page
 
Update _Layout.cshtml page to add new tab/hyperlink to get list of users.
 
Code for _Layout.cshtml
  1. <!DOCTYPE html>    
  2. <html lang="en">    
  3. <head>    
  4.     <meta charset="utf-8" />    
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0" />    
  6.     <title>@ViewData["Title"] - CookieAuthenticationDemo</title>    
  7.     <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />    
  8.     <link rel="stylesheet" href="~/css/site.css" />    
  9. </head>    
  10. <body>    
  11.     <header>    
  12.         <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">    
  13.             <div class="container">    
  14.                 <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">CookieAuthenticationDemo</a>    
  15.                 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"    
  16.                         aria-expanded="false" aria-label="Toggle navigation">    
  17.                     <span class="navbar-toggler-icon"></span>    
  18.                 </button>    
  19.                 <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">    
  20.                     <ul class="navbar-nav flex-grow-1">    
  21.                         <li class="nav-item">    
  22.                             <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>    
  23.                         </li>    
  24.                         <li class="nav-item">    
  25.                             <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Users">Users</a>    
  26.                         </li>    
  27.                     </ul>    
  28.                 </div>    
  29.             </div>    
  30.         </nav>    
  31.     </header>    
  32.     <div class="container">    
  33.         <main role="main" class="pb-3">    
  34.             @RenderBody()    
  35.         </main>    
  36.     </div>    
  37.     
  38.     <footer class="border-top footer text-muted">    
  39.         <div class="container">    
  40.             © 2020 - CookieAuthenticationDemo - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>    
  41.         </div>    
  42.     </footer>    
  43.     <script src="~/lib/jquery/dist/jquery.min.js"></script>    
  44.     <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>    
  45.     <script src="~/js/site.js" asp-append-version="true"></script>    
  46.     @RenderSection("Scripts", required: false)    
  47. </body>    
  48. </html>   
Run your application
 
After successfully running your application, the output of your application should be like the below screen,
 
Cookie Authentication In .NET Core 3.0
Click on Users tab to get a list of users, it will open a login page to log in a user.
 
Q) Why will it ask for login?
 
Ans -  [Authorize] attribute restrict to access data/information for unauthorized requests and redirect to login page to check if user is valid or not. In our case we have added this attrubute over the Users action method of HomeController. 
 
Cookie Authentication In .NET Core 3.0
Provide username and password to login. After login, it will create a cookie in the browser like below.
 
Cookie Authentication In .NET Core 3.0
 
Click on the Users tab again and now you can find the final result of user list without asking for login screen.
 
Cookie Authentication In .NET Core 3.0
To test your cookie base authentication, you can delete that created cookie from browser and click on the Users tab. It will ask for login again.
 

Summary

 
In this article, I discussed how to add cookie based authentication in .net core 3.0. We have also created a user login form to login a user to our application to access useful information. Please find attached code for better understanding.