LESSON 2 OF 15

Integrating Identity into an ASP.NET Core Project

Learn how to add ASP.NET Core Identity to a project using MSSQL and Entity Framework Core, configure a custom user, create IdentityDbContext, and apply migrations.

55 dk 100

Introduction

An ASP.NET Core application needs a reliable identity infrastructure to manage user accounts securely and consistently. ASP.NET Core Identity provides ready-made services and data models for managing users, passwords, roles, claims, token providers, and sign-in information.

In this lesson, we will integrate ASP.NET Core Identity into an application that uses MSSQL and Entity Framework Core. We will add the required packages, create a custom IdentityUser class, and define an IdentityDbContext. We will then register the services in Program.cs and use Entity Framework Core migrations to create the Identity schema in SQL Server.

We will not build registration or login screens yet. Instead, we will establish the core infrastructure that will support those features in later lessons.

Note: The examples use the .NET 8 or later ASP.NET Core minimal hosting model. Keep package versions compatible with the target framework used by your project.

Understanding the Identity architecture

ASP.NET Core Identity brings together two important areas. The first is the set of application services used for user and password management. The second is the store layer that persists this information. When the Entity Framework Core provider is used, the store can persist Identity data in SQL Server.

The default Identity model includes the following concepts:

  • IdentityUser: Represents a user and fields such as user name, email address, password hash, security stamp, and lockout information.
  • IdentityRole: Stores roles such as administrator or editor.
  • IdentityUserRole: Represents the many-to-many relationship between users and roles.
  • IdentityUserClaim: Stores additional permissions or profile information associated with a user.
  • IdentityUserLogin: Stores information related to external login providers.
  • IdentityUserToken: Stores token data associated with a user.

Instead of creating these tables manually, it is safer to expose the Identity model through Entity Framework Core and use migrations. This keeps the database schema trackable in code, allows changes to be versioned, and supports controlled deployment across environments.

Preparing the project and packages

For this example, assume that we are using an ASP.NET Core Web API project named SecureApi. If you already have a project, you can add only the required packages.

dotnet new webapi -n SecureApi
cd SecureApi

Add the SQL Server and Identity packages:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore

The Microsoft.AspNetCore.Identity.EntityFrameworkCore package connects the core Identity services to an Entity Framework Core store. The SQL Server provider allows the DbContext to communicate with MSSQL. The command-line tools are used to create and apply migrations.

After adding the packages, the following folder structure is enough to begin:

SecureApi/
  Data/
  Models/
  Program.cs
  appsettings.json

Creating a custom user class

The default IdentityUser class is sufficient for simple scenarios. Most applications, however, need additional information such as a department, display name, or creation date. We can create our own user class by inheriting from IdentityUser.

using Microsoft.AspNetCore.Identity;

namespace SecureApi.Models;

public class AppUser : IdentityUser
{
    public string DisplayName { get; set; } = string.Empty;
    public DateTime CreatedAtUtc { get; set; } = DateTime.UtcNow;
}

When IdentityUser is used without a generic key type, the user key defaults to a string. As a result, the user identifiers in SQL Server are created as text-based keys. If your application requires another key type, use IdentityUser<TKey> together with the corresponding generic IdentityDbContext types.

Using UTC for CreatedAtUtc helps keep timestamps consistent across servers and user time zones. In production applications, do not allow clients to overwrite this value through request models.

Creating IdentityDbContext

Next, create the database context that contains the Identity model.

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using SecureApi.Models;

namespace SecureApi.Data;

public class ApplicationDbContext : IdentityDbContext<AppUser>
{
    public ApplicationDbContext(
        DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<AppUser>()
            .Property(user => user.DisplayName)
            .HasMaxLength(120);
    }
}

The most important detail is the call to base.OnModelCreating(builder). This call adds Identity's user, role, claim, and token relationships to the Entity Framework model. If it is omitted, Identity's default relationships and indexes may not be configured correctly.

Your application may later include business entities such as orders, products, or audit records. These can be added to the same ApplicationDbContext or maintained in separate contexts. Keeping Identity tables in the same database as application data is common, but a separate database may be more appropriate depending on security, scaling, and operational requirements.

Configuring the connection string

Add a SQL Server connection string to appsettings.json for local development:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=SecureApiDb;Trusted_Connection=True;TrustServerCertificate=True;MultipleActiveResultSets=true"
  }
}

Do not place production passwords or sensitive connection details in source code. Use User Secrets, environment variables, or a secure secret-management system. TrustServerCertificate=True may simplify local development, but production TLS certificates and server validation should follow your organization's security policy.

Registering services in Program.cs

Register Entity Framework Core and Identity in the dependency injection container:

using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using SecureApi.Data;
using SecureApi.Models;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration
    .GetConnectionString("DefaultConnection")
    ?? throw new InvalidOperationException(
        "The DefaultConnection connection string was not found.");

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

builder.Services
    .AddIdentityCore<AppUser>(options =>
    {
        options.User.RequireUniqueEmail = true;
        options.Password.RequiredLength = 8;
        options.Password.RequireDigit = true;
        options.Password.RequireUppercase = true;
        options.Password.RequireLowercase = true;
        options.Password.RequireNonAlphanumeric = false;
    })
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.MapControllers();

app.Run();

In this example, AddIdentityCore registers the core Identity services. AddRoles enables role management, while AddEntityFrameworkStores specifies that users and roles will be persisted through ApplicationDbContext. AddDefaultTokenProviders registers token providers that can later support email confirmation, password reset, or two-factor authentication.

We have not added a cookie or JWT authentication scheme yet. Identity's user and password management services are separate from the authentication scheme used by the application. Cookie and JWT configuration will be covered in later lessons.

Creating a migration and updating the database

With the context and Identity services configured, create the first migration:

dotnet ef migrations add CreateIdentitySchema

This command creates migration classes and a model snapshot in a Migrations folder. Inspect the generated files. The migration should contain operations that create the Identity tables and their foreign key relationships.

Apply the migration to the development database:

dotnet ef database update

After the command completes successfully, the SecureApiDb database will generally contain tables such as AspNetUsers, AspNetRoles, AspNetUserRoles, AspNetUserClaims, AspNetUserLogins, AspNetUserTokens, and AspNetRoleClaims. Entity Framework Core also creates the __EFMigrationsHistory table to track applied migrations.

Creating migration files is not enough. They must be applied to the target database as part of a controlled CI/CD or deployment process. In production, applying an unreviewed migration without a backup or rollback plan is risky. Migration files should normally be committed to source control because they describe versioned schema changes.

Reviewing Identity tables and password storage

The AspNetUsers table does not store passwords in plain text. Identity uses password hashes and related security data for verification. Therefore, even administrators should not be able to retrieve a user's actual password from the database.

When making email addresses or user names unique, consider both Identity options and database indexes. RequireUniqueEmail = true enables application-level validation, while indexes created by the migration help enforce database-level integrity.

You can rename tables or customize columns, but keeping the default naming convention is often easier for teams to understand and maintain. If customization is required, perform it in OnModelCreating and generate controlled migrations for the changes.

Common mistakes

  • Using a regular DbContext instead of IdentityDbContext: Identity entities are not added to the model, so the migration does not create the required tables.
  • Forgetting base.OnModelCreating: Identity's default relationships and indexes may be skipped.
  • Using the wrong connection name: The key passed to GetConnectionString("DefaultConnection") must match the key in appsettings.json.
  • Running migration commands from the wrong project: Run the command in the directory containing the relevant project file, or specify --project and --startup-project.
  • Committing production connection details: Store connection strings and secrets through secure configuration mechanisms.
  • Hashing passwords manually: Use Identity's UserManager and password validation services instead of inventing a custom hashing implementation.
  • Deleting the database for every change: APIs such as EnsureDeleted should be limited to controlled testing scenarios.

Short practice exercise

Complete the following task in a new practice project:

  1. Add a non-nullable property named Department, with a maximum length of 80 characters, to AppUser.
  2. Configure the maximum length of this property in ApplicationDbContext.
  3. Enable unique email addresses through the Identity options.
  4. Create a migration named ProfileDepartment.
  5. Apply the migration to the SQL Server database.
  6. Use SQL Server Object Explorer or another database tool to verify that the new column exists in the AspNetUsers table.

After completing the exercise, answer this question: Why does adding a property to the user model not automatically create a column in the database? The expected answer is that the model change must be converted into a migration and then applied to the database schema.

Conclusion

In this lesson, we added ASP.NET Core Identity to a project using MSSQL and Entity Framework Core. We created a custom AppUser, connected the Identity model to an IdentityDbContext, registered the required services, and created the initial Identity tables in SQL Server through migrations.

This infrastructure will support user registration, login, logout, password validation, cookie authentication, roles, and claims in later lessons. The key principles are to use Identity's built-in services, avoid implementing password storage yourself, protect connection secrets, and keep database schema changes traceable through migrations.

Sources