ASP.NET Core Identity Setup

ASP.NET Core Identity Setup

In this article, I will discuss the ASP.NET Core Identity Setup in your ASP.NET Core MVC or ASP.NET Core Web API Applications. I will use SQL Server as the database, Entity Framework Core Code First Approach, ASP.NET Core MVC Application, and ASP.NET Core Identity here. 

Let us proceed and see the step-by-step process of setting up ASP.NET Core Identity in an ASP.NET Core MVC Application. The process will also be the same for ASP.NET Core Web API. I am using ASP.NET Core MVC here because I want to demonstrate both the frontend and backend. With ASP.NET Core Web API, we can only develop the backend.

Step 1: Create a New ASP.NET Core Project

Let us first create a new ASP.NET Core Application using the ASP.NET Core Web App (Model-View-Project) template.

  • Use Visual Studio or dotnet CLI to create a new ASP.NET Core Web App (Model-View-Controller) project.
  • Name the project, e.g., ASPNETCoreIdentityDemo.
  • Select Authentication Type: None, as we will manually add Identity ourselves.

This gives you a clean project with the MVC pattern ready to integrate Identity. With this, the project should be created with the following structure.

ASP.NET Core Identity Setup

Step 2: Install Required NuGet Packages

ASP.NET Core Identity needs three packages to be installed in our ASP.NET Core Web application. These packages are as follows:

  • Microsoft.AspNetCore.Identity.EntityFrameworkCore: This package integrates ASP.NET Core Identity with Entity Framework Core. It provides the necessary implementation to store user, role, and other identity-related data in a database using EF Core. 
  • Microsoft.EntityFrameworkCore.SqlServer: This package is the Entity Framework Core database provider for Microsoft SQL Server. It allows the application to use Entity Framework Core to interact with SQL Server.
  • Microsoft.EntityFrameworkCore.Tools: This package provides supports for database migration, which help create and update database schemas. 

These packages add the core functionality you need to implement Identity backed by SQL Server.

How to install:

Open the Package Manager Console in Visual Studio and then execute the following commands to install the above packages:

  • Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Install-Package Microsoft.EntityFrameworkCore.SqlServer
  • Install-Package Microsoft.EntityFrameworkCore.Tools
Step 3: Define Database Context Class

The IdentityDbContext class in ASP.NET Core Identity plays an essential role in integrating the Identity membership management system with Entity Framework Core. This IdentityDbContext class inherits from DbContext and is designed to manage the database context for the identity data. 

Our application Context class needs to be inherited from the IdentityDbContext class instead of the DbContext class. This is because IdentityDbContext inherits from the Entity Framework Core DbContext class and provides all the DbSet properties needed to manage the Identity Tables.

First, create a folder named Data in the Project root directory. Then, create a class file named ApplicationDbContext.cs within the Data folder and copy and paste the following code.

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace ASPNETCoreIdentityDemo.Data
{
    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
    }
}

Note: This class becomes the EF Core database context responsible for accessing Identity tables. Later, this context will be injected wherever needed.

Step 4: Configuring Connection String in AppSettings.json file:

Next, open the appsettings.json file and copy and paste the following code. Here, we are providing the connection string name SQLServerIdentityConnection, which contains the connection string of our SQL server database, where we will create our Identity database.

{
  "ConnectionStrings": {
    "SQLServerIdentityConnection": "Server=LAPTOP-6P5NK25R\\SQLSERVER2022DEV;Database=IdentityCoreDB;Trusted_Connection=True;TrustServerCertificate=True;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}
Step 5: Configure ASP.NET Core Identity, Entity Framework Core, and Middleware

To enable authentication and user management in our ASP.NET Core MVC application, we need to configure the Identity services, register the Entity Framework Core context for data access, and add the authentication and authorization middleware into the HTTP request processing pipeline.

Register Entity Framework Core with SQL Server

First, configure EF Core to use SQL Server by registering our custom ApplicationDbContext in the dependency injection container. This context will be responsible for managing our Identity-related database tables.

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("SQLServerIdentityConnection")));

Here, the connection string SQLServerIdentityConnection should be defined in the appsettings.json and points to the SQL Server database where Identity data will be stored.

Register ASP.NET Core Identity Services

Next, we need to configure ASP.NET Core Identity services in the DI container. This enables user and role management along with default Identity features such as password hashing and validation.

builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

IdentityUser and IdentityRole represent the default user and role entities. AddEntityFrameworkStores<ApplicationDbContext>() instructs Identity to use EF Core context (ApplicationDbContext) for storing user and role data.

Add Authentication and Authorization Middleware

After registering the services, add the middleware components in the HTTP request pipeline to enable authentication and authorization capabilities:

  • app.UseAuthentication(); // Enables the authentication system to validate user credentials
  • app.UseAuthorization(); // Enables authorization checks for access control based on roles or policies

Important Note: Place these middleware calls after the routing middleware (app.UseRouting()) but before the MVC routing middleware (app.MapControllerRoute(…)) so that the Identity system can authenticate and authorize users before requests reach your controllers.

Why this order?
  • The app.UseRouting() middleware matches the incoming request to a specific endpoint (e.g., a controller action).
  • Authentication (app.UseAuthentication()) needs to happen after routing because it uses information about the endpoint and the request to authenticate the user properly.
  • Authorization (app.UseAuthorization()) runs after authentication and uses the authenticated user information to check whether access to the requested endpoint is allowed based on roles, policies, or claims.
  • Finally, app.MapControllerRoute(…) executes the matched endpoint (controller action) only after authentication and authorization are successfully completed.
Complete Program Class:

The complete code of the Program class is as follows:

using ASPNETCoreIdentityDemo.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

namespace ASPNETCoreIdentityDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            // Register Entity Framework Core with SQL Server
            builder.Services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(builder.Configuration.GetConnectionString("SQLServerIdentityConnection")));

            // Register ASP.NET Core Identity Services
            builder.Services.AddIdentity<IdentityUser, IdentityRole>()
                    .AddEntityFrameworkStores<ApplicationDbContext>();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            // Add Authentication and Authorization Middleware
            app.UseAuthentication();
            app.UseAuthorization();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            app.Run();
        }
    }
}

This setup ensures:

  • EF Core is configured to connect with your database.
  • Identity services are wired up to manage users and roles.
  • Middleware correctly authenticates and authorizes requests to secure your application.
Step 6. Create ASP.NET Core Identity Database Schema

Next, we need to generate the Migration file and update the database. So, open the Visual Studio Package Manager Console and execute the following Add-Migration and Update-Database commands.

Create ASP.NET Core Identity Database Schema

Now, if you verify the database, you should see the following tables in the IdentityCoreDB database.

ASP.NET Core Identity Setup in your ASP.NET Core MVC or ASP.NET Core Web API Applications

Differences Between AddIdentity and AddIdentityCore in ASP.NET Core Identity

ASP.NET Core Identity provides two primary methods for registering identity services into the built-in dependency injection (DI) container: AddIdentity and AddIdentityCore. Although they sound similar, these methods serve different purposes and offer different levels of functionality designed for different application scenarios.

AddIdentity

AddIdentity sets up the complete and full-featured ASP.NET Core Identity system in your application.

What it registers:
  • User and role management services, including UserManager, RoleManager, and SignInManager.
  • Authentication handlers for cookie-based authentication are used by default.
  • Services for managing security stamps, password hashing, claims, tokens, and lockouts.
  • The default UI supports common Identity operations such as user registration, login, logout, password recovery, email confirmation, and more (when using Identity UI packages).
Ideal use case:
  • Applications that require a complete user management system with built-in user interface components for registration, login, and account management. Typically, this applies to ASP.NET Core MVC web applications or Razor Pages apps where views and controllers handle the UI.
  • Use AddIdentity when you want an all-in-one, ready-to-use Identity system with integrated cookie authentication and UI scaffolding.
Syntax to use AddIdentity:

Syntax to use AddIdentity

AddIdentityCore

AddIdentityCore provides a minimal and lightweight subset of ASP.NET Core Identity services, focusing only on the core user and role management features.

What it registers:
  • Core services such as UserManager and RoleManager for managing users and roles.
  • Does NOT register SignInManager, cookie authentication handlers, or UI-related services.
  • It provides essential password hashing, user validation, and token providers, but leaves out authentication flow details.
Ideal use case:
  • Applications like API Backends (e.g., ASP.NET Core Web API), where authentication is handled differently, commonly via JWT tokens, OAuth, or other token-based schemes. In these projects, we often implement our own authentication logic and do not need cookie-based sign-in or built-in UI.
  • Use AddIdentityCore when you want Identity’s core user and role features without the extra overhead of sign-in and UI services. This allows more control over authentication, perfect for stateless APIs.
Syntax to use AddIdentityCore:

Syntax to use AddIdentityCore

Practical Example Scenarios

Scenario 1: I am building a web application in ASP.NET Core MVC and want to quickly enable user registration, login, and password reset with built-in pages and cookies.

  • Use: AddIdentity

Scenario 2: I am building a REST API that will be consumed by a mobile app and a React frontend. Authentication will use JWT tokens, and the UI is handled entirely by the client.

  • Use: AddIdentityCore (with JWT authentication)
What is the Default Primary Key Column Type in ASP.NET Core Identity?
  • By default, ASP.NET Core Identity uses a string type as the primary key for its entities (like users and roles).
  • Specifically, the primary key type is string, and the IDs are typically GUIDs (Globally Unique Identifiers) stored as strings.
  • For example, the default user ID property in the IdentityUser class is: public virtual string Id { get; set; }
  • This means that Identity creates tables where the primary key columns (like Id in the AspNetUsers table) are of type nvarchar(450) in SQL Server.
Why Use string by Default?
  • Using a string-based GUID as the key allows easy generation of unique identifiers without needing a central numeric ID generator.
  • It also fits nicely in distributed systems and avoids issues with integer overflow.
  • It simplifies integration with external authentication providers (which often use string IDs).
Why Specify IdentityUser and IdentityRole When Registering Identity Services?

When we register ASP.NET Core Identity in the DI container like this:

builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

We are explicitly telling ASP.NET Core which user and role entity types our Identity system should use.

Reasons for Specifying These Types

Identity is a Generic Framework. ASP.NET Core Identity is designed to be extensible and flexible. It uses generic types to represent the user and role entities:

  • TUser represents the user entity type.
  • TRole represents the role entity type.

By specifying <IdentityUser, IdentityRole>, we tell the framework:

  • Use the built-in IdentityUser class for users
  • Use the built-in IdentityRole class for roles
Allows Customization

If you want to extend the user or role entity with custom properties (e.g., adding FirstName, LastName to the user), you need to create your own classes by inheriting from IdentityUser or IdentityRole. Then you need to specify your custom classes here, so Identity knows to work with your types. For example:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();
Supports Different Primary Key Types

These classes also define the primary key type for users and roles. For example:

  • IdentityUser uses a string as the primary key type.
  • You might have a custom class like IdentityUser<int> if you want an integer key.

Specifying the types makes Identity and EF Core aware of what key type to expect.

In the next article, I will discuss ASP.NET Core Identity Tables and their usage in detail. In this article, I try to explain ASP.NET Core Identity Setup in ASP.NET Core MVC or Web Applications. I hope you enjoy this ASP.NET Core Identity Setup in ASP.NET Core MVC or Web Applications article.

4 thoughts on “ASP.NET Core Identity Setup”

  1. blank

    If update-database produces an error that includes “The server was not found or was not accessible.”, try:
    1. Run remove-migration
    2. In the connection string from step 5, replace “LAPTOP-6P5NK25R” with “(localdb)”
    3. Try Step 8 again

  2. blank

    If add-migration produces the error “Error: Connection string ‘SQLServerIdentityConnection’ not found.”, go back to Step 5 and remove the space from the end of “SQLServerIdentityConnection “.

  3. blank

    Want to master ASP.NET Core Identity?
    Check out our latest video: ASP.NET Core Identity Introduction, Setup, and Customization
    Learn step-by-step how to set up and customize ASP.NET Core Identity for secure login, role management, and more.
    Watch now 👉 https://www.youtube.com/watch?v=WGd9nyoQMjg

    Boost your .NET skills with practical, easy-to-follow tutorials from Dot Net Tutorials! Don’t forget to like, share, and subscribe for more .NET tutorials and videos!

Leave a Reply

Your email address will not be published. Required fields are marked *