DEV Community

Cover image for Step by step guide on how to add authentication to Asp.Net Core MVC and how to customise it
Mohamad Lawand
Mohamad Lawand

Posted on • Updated on

Step by step guide on how to add authentication to Asp.Net Core MVC and how to customise it

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

The 3 things that we will need before we start:

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

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(options => {
options.Password.RequireDigit = true;
options.Password.RequireUppercase = true;
}).AddEntityFrameworkStores() .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 SignInManager
@inject UserManager 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 _userManager;
private readonly SignInManager _signInManager;
private readonly ILogger _logger;

public LoginModel(SignInManager signInManager,
ILogger logger,
UserManager 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 _signInManager;
private readonly UserManager _userManager;
private readonly ILogger _logger;
private readonly IEmailSender _emailSender;

public RegisterModel(
UserManager userManager,
SignInManager signInManager,
ILogger 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

__









__

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

Top comments (0)