Step by step guide on how to add authentication to Asp.Net Core MVC and how to customise it
Tags: beginners, dotnet, aspnetcore, authentication
Published: 2021-01-10 10:37:35

In this article we will be exploring how we can add authentication to Asp.Net Core application you can watch the full tutorial on Youtube as well 

{% youtube 9nPS_d8scs0 %}

The 3 things that we will need before we start:
- Visual Studio code (https://code.visualstudio.com)
- Dotnet core SDK (https://dotnet.microsoft.com/download)
- Download sqllite browser https://sqlitebrowser.org/dl/

For this sample application we will be using SQLLite as our local database. After installing all of requirements, we need to make sure that the dotnet SDK has been installed successfully, we need to open the terminal and check if the dotnet SDK is installed successfully by checking the dotnet version.

__dotnet --version__

Now we need to install the entity framework tool
__dotnet new mvc -n “SampleWebAuth” -lang “C#” -au individual__

We open visual studio code. In this project we will utilise AspNetCore Identity Razor Class Library for our authorisation and authentication, the Razor Class Library comes bundled with the project as we can see it has been been created inside the Areas folder ⇒ identity

To get started we need to have the terminal ready in VS code, we can go to view and click on view terminal

Build project and run it
__dotnet build__
__dotnet run__

After we make sure that the application is running, we need to setup the database for the Microsoft identity infrastructure. To do that we need run the initial database migration

__dotnet ef migrations add “Initial migration”__
__dotnet ef database update__

Lets open the database in SQLLite browser and check the changes in the database. We can see the tables has been created and everything is initialised

Inside the Model folder we need to add a new class called AdvanceUser which will inherit from IdentityUser which will contain the new properties
Right click on the Model folder ⇒ Add file ⇒ General ⇒ Empty class will give it the name AdvanceUser, then add the code below:

__public class AdvanceUser : IdentityUser
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string Mobile { get; set; }
}__

After saving the AdvanceUser class we need to update the ApplicationDbContext class to inject these changes into the database and utilise them across the app.
Open then ApplicationDbContext class inside the Data folder and change the line 10 to the following

__public class ApplicationDbContext : IdentityDbContext<AdvanceUser>__

We need to update the startup class with the code below

_// Here we are hooking up the new AdvanceUser features to the identity middleware — We can add options inside the options function_
__services.AddIdentity<AdvanceUser, IdentityRole>(options => {
options.Password.RequireDigit = true;
options.Password.RequireUppercase = true;
}).AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders().AddDefaultUI();__

_// We need the razor pages support after the scaffolding of the identity service_ 
__services.AddRazorPages();__

Save the class, now we need to create a new migration script to update the database, inside the terminal write the following code

__dotnet ef migrations add “Updated Identity” 
dotnet ef database update
dotnet build 
dotnet run__

Lets open the database in SQLLite browser and check the changes in the database. and lets open the AspNetUser and we can see now the 3 new fields has been added.

Lets try registering a user and login.
We need now to update the registration page, Identity library is a RazorClassLibrary we need to use the dotnet sdk to generate the files so we can edit them
We need to install the libraries which will allow us to Scaffold the pages

__dotnet tool install -g dotnet-aspnet-codegenerator
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet add package Microsoft.AspNetCore.Identity.UI
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools__

Once all these packages are added and the tool is generated we can check the csproj file to make sure all of the package are there. Now that everything is ready we need to run the command to Scaffold the Identity

__dotnet aspnet-codegenerator identity -dc SampleWebAuth.Data.ApplicationDbContext — files “Account.Register;Account.Login”__

we can use — useDefaultUI will generate the basic version of the Identity library for more information please find the link in the video description.
Now we need to update the _loginpartial view to use the AdvanceUser class, you will need to go to Views ⇒ Shared ⇒ _loginPartial

__@using Microsoft.AspNetCore.Identity
@inject SignInManager<AdvanceUser> SignInManager
@inject UserManager<AdvanceUser> UserManager__

After updating the partial view we need to update the login and the register views, we need to navigate to
Area ⇒ Identity ⇒ Pages ⇒ Account ⇒ Login/Register
For the login page we need to update login.cshtml.cs with the below

__private readonly UserManager<AdvanceUser> _userManager;
private readonly SignInManager<AdvanceUser> _signInManager;
private readonly ILogger<LoginModel> _logger;__

__public LoginModel(SignInManager<AdvanceUser> signInManager, 
ILogger<LoginModel> logger,
UserManager<AdvanceUser> userManager)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}__

We need to open the register.cshtml.cs page and add the SignInManager and the UserManager with the AdvanceUser class instead of IdentityUser and add the 3 new fields to the InputModel

__private readonly SignInManager<AdvanceUser> _signInManager;
private readonly UserManager<AdvanceUser> _userManager;
private readonly ILogger<RegisterModel> _logger;
private readonly IEmailSender _emailSender;__

__public RegisterModel(
UserManager<AdvanceUser> userManager,
SignInManager<AdvanceUser> signInManager,
ILogger<RegisterModel> logger,
IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_emailSender = emailSender;
}__

__public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = “Email”)]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = “The {0} must be at least {2} and at max {1} characters long.”, MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = “Password”)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = “Confirm password”)]
[Compare(“Password”, ErrorMessage = “The password and confirmation password do not match.”)]
public string ConfirmPassword { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Mobile { get; set; }
}__

We need also to update OnPostAsync action

__var user = new AdvanceUser { UserName = Input.Email, Email = Input.Email, FirstName = Input.FirstName, LastName = Input.LastName, Mobile = Input.Mobile };__

Now we need to update the view to reflect these changes, we will need to open Register.cshtml and edit the html as follow

__<div class=”form-group”>
<label asp-for=”Input.FirstName”></label>
<input asp-for=”Input.FirstName” class=”form-control” />
<span asp-validation-for=”Input.FirstName” class=”text-danger”></span>
</div>
<div class=”form-group”>
<label asp-for=”Input.LastName”></label>
<input asp-for=”Input.LastName” class=”form-control” />
<span asp-validation-for=”Input.LastName” class=”text-danger”></span>
</div>
<div class=”form-group”>
<label asp-for=”Input.Mobile”></label>
<input asp-for=”Input.Mobile” class=”form-control” />
<span asp-validation-for=”Input.Mobile” class=”text-danger”></span>
</div>__

Now we need to run the application and test everything
__dotnet build
dotnet run__

Thank you for taking the time and read this article.
You can find the source code for this sample project in Github using the following link: https://github.com/mohamadlawand087/v3-AspNetCoreAuthentication