(C# ASP.NET Core) Collecting the Pre-requisites for Identity based Authentication

We shall create an identity based project from scratch. Although, visual studio provides a scaffolding for all the various modules, but personally I find all that very difficult to integrate with my own projects and my own css files. That's the motivation for starting from scratch. It will be a series of tutorials. In this first tutorial, I shall add nuget packages, followed by an IdentityDbContext, and finally run a migration to create the database on local sql server.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

Table of Contents (top down ↓)

Create a Simple ASPNET Core Project

Start by creating a simple ASP.NET Core Project consisting of just one page called Index. This page displays a welcome message.

This is almost a blank application, and we shall build identity based authentication from ground zero.


@page

<h1>Welcome to Identity</h1>

Next use the menu View > SQL Server Object Explorer to open the SQL Server Object Explorer.

Locate the MSSQLLocalDB instance and right click to open the context menu. Click properties and open the properties of this instance. Find the entry for connection string and copy the connection string to clipboard.

Come to the solution explorer and open the appSettings development json file. Add a section called ConnectionStrings and give any name to your connection string, such as MyConnString and set its value by pasting the string that you copied in the previous step. Notice that I have set the property Initial Instance to myauthdb - so this shall be the name of my database.

  
  // appsettings.development.json 

  {
  "ConnectionStrings": {

    "MyConnString": "Data Source=(localdb)\\MSSQLLocalDB;
    Initial Catalog=myauthdb;Integrated Security=True;"

  },

  "DetailedErrors": true,

  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft.AspNetCore": "Error"
    }
  }
}
  

We have added the connection string to this json file so that we do not have to hard-code it anywhere in our code. This will be picked during development environment. And, for production, the connection string can be saved as an environment variable on the server machine.

Video Explanation (see it happen!)

Please watch the following youtube video:

Add Nuget Packages

Open the package manager console, and type the following command to add the nuget package for entity framework core.

PM> Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore

Hit enter and allow it to complete successfully.

Repeat the same installation for SQL Server, AspNetCore UI and for the EF Core tools.

 

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Install-Package Microsoft.AspNetCore.Identity.UI

Install-Package Microsoft.EntityFrameworkCore.Tools

The purpose of adding SqlServer is to add support for SQL Server so that we can easily see the tables and data in visual studio.

We have added Identity so that we can add support for Identity API in our project.

The purpose of adding EF Core Tools is to add support for database migrations.

Add IdentityDbContext

Open the solution explorer, and add a folder called Data, and then add a class called MyAuthContext to this folder.

The code for the class is shown here.

using Microsoft.AspNetCore.Identity;

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

using Microsoft.EntityFrameworkCore;

namespace MyRazorApp.Data
{

  public class MyAuthContext : IdentityDbContext
  {

    private readonly IConfiguration _cfg;

    public MyAuthContext(IConfiguration cfg)
    {

      _cfg = cfg;

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {

      optionsBuilder.UseSqlServer(_cfg.GetConnectionString("MyConnString"));

    }

    protected override void OnModelCreating(ModelBuilder builder)
    {

      base.OnModelCreating(builder);

      builder.Entity<IdentityUser>().ToTable("AspNetUsers");

    }

    public DbSet<IdentityUser>? AspNetUsers { get; set; }
  }

}

First we obtain IConfiguration through the constructor based dependency injection. See the chapter on Database Connectivity for details of the repository pattern and dependency injection.

The OnConfiguring method is used to set SQLServer as our database. We have use IConfiguration for reading the connection string from appSettings json file. This string is stored in appSettings development file during development. The same string can be stored in environment variables when the application is run in a production scenario.

A table of the name AspNetUsers is specified in the OnModelCreating override.

Lastly, a DbSet property has been added for accessing the above table.

Configure the Startup Class

Come to the solution explorer and open the Program.cs file.

Add MyAuthContext to the services container. This is sufficient for this tutorial. We will keep adding more to this file in the later tutorials.

// VS 2022 and later, .NET 6 and later 
using Microsoft.AspNetCore.Identity;

using Microsoft.EntityFrameworkCore;

using MyRazorApp.Data;

var builder = WebApplication.CreateBuilder();

// add this 
builder.Services.AddDbContext<MyAuthContext>();

builder.Services.AddRazorPages();

var app = builder.Build();

app.MapRazorPages();

app.Run();

Create the Database and its Tables

Open the package manager console and type the add-migration command for creating the database and all the necessary tables. Please refer the chapter on Migrations where we have covered the whole concept in great detail.


PM> Add-Migration InitialCreate

Hit enter and allow it to complete.

If everything goes fine, then a migrations folder will appear in the solution explorer. Nothing needs to be done with this. Let it stay here.

Again open package manager console to execute the migration. Type the command update database


PM> Update-Database

Hit enter and allow it to complete.

Next let us verify the successful completion. Open SQL Server Object Explorer, and refresh it. If everything went fine, then the database myauthdb will appear visible.

This completes the initial setup. Repeat these steps on your own machine. You can even download the project from the attached downloads. The project is completed till this stage. Thanks!


This Blog Post/Article "(C# ASP.NET Core) Collecting the Pre-requisites for Identity based Authentication" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.