Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 52 ยท Authentication and Authorization

ASP.NET Core Identity Overview

A tour of ASP.NET Core Identity: users and roles, password hashing, lockout, two-factor authentication, passkeys and external logins, with runnable stand-ins.

So far you have written handlers that recognize credentials, but you have not dealt with the part that comes first: where do users come from? Someone has to store accounts, hash passwords, throttle guessing attacks, send confirmation emails, and handle forgotten passwords and second factors. ASP.NET Core Identity is the framework's answer. It is a membership system that gives you a user store, password and role management, and the sign-in logic, and it plugs into the cookie and authorization features you already know.

Identity needs a database provider (usually Entity Framework Core) and NuGet packages, neither of which the single-file runner on this site can load. So this lesson is mostly read-only: the real configuration is shown as code to copy into a project. To keep it hands-on, the two runnable examples are faithful stand-ins that implement the ideas inside Identity (password hashing, lockout, roles and one-time codes) in plain C#. They teach how the machinery works. They are not a replacement for the library, and you should never roll your own authentication for production.

What Identity gives you

flowchart TD
    APP["Your endpoints and pages"] --> SM["SignInManager<br/>(password check, lockout, 2FA, cookies)"]
    APP --> UM["UserManager<br/>(create users, passwords, roles, claims, tokens)"]
    UM --> PH["IPasswordHasher"]
    UM --> ST["User store<br/>(EF Core by default)"]
    SM --> UM
    SM --> CK["Cookie authentication"]
    ST --> DB[("Database<br/>AspNetUsers, AspNetRoles, ...")]

Your code talks to two managers; they use a password hasher and a pluggable store.

The core types:

  • IdentityUser is the user entity (id, user name, email, password hash, lockout and two-factor fields). You usually subclass it to add your own columns, such as DisplayName.
  • IdentityRole is a named role; a user can be in several.
  • UserManager<TUser> creates and updates users, sets passwords, manages roles and claims, and generates tokens for email confirmation and password reset.
  • SignInManager<TUser> signs a user in (checks the password, applies lockout, handles second factors, then issues the cookie).
  • RoleManager<TRole> manages roles themselves.
  • The store is the persistence layer. The default EF Core store uses tables such as AspNetUsers, AspNetRoles, AspNetUserRoles, AspNetUserClaims and AspNetUserLogins.

Identity's job ends once the user is signed in with a cookie. From then on the request carries a normal ClaimsPrincipal, and everything from Authorization: Roles, Policies and Handlers works unchanged: roles stored by Identity simply become role claims.

Setting it up (read-only)

In a project with the Microsoft.AspNetCore.Identity.EntityFrameworkCore package, the setup is a few lines:

C#
public class AppUser : IdentityUser
{
    public string? DisplayName { get; set; }
}

public class AppDbContext(DbContextOptions<AppDbContext> options)
    : IdentityDbContext<AppUser>(options);

// Program.cs
builder.Services.AddDbContext<AppDbContext>(o =>
    o.UseSqlite(builder.Configuration.GetConnectionString("Default")));

builder.Services
    .AddIdentityApiEndpoints<AppUser>(options =>
    {
        options.Password.RequiredLength = 10;
        options.User.RequireUniqueEmail = true;
        options.SignIn.RequireConfirmedEmail = true;
        options.Lockout.MaxFailedAccessAttempts = 5;
        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
    })
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<AppDbContext>();

builder.Services.AddAuthorization();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapGroup("/account").MapIdentityApi<AppUser>();   // register, login, refresh, ...
app.MapGet("/me", (ClaimsPrincipal user) => user.Identity!.Name).RequireAuthorization();

Two entry points exist, and the choice depends on your client:

  • AddDefaultIdentity / AddIdentity is the cookie-based flavor behind server-rendered sites and Blazor. The project templates (for example a Blazor Web App created with individual accounts) generate the register, login, manage-account and confirm-email pages for you.
  • AddIdentityApiEndpoints plus MapIdentityApi exposes JSON endpoints (/register, /login, /refresh, /confirmEmail, /manage/info, ...) for single-page apps and mobile clients. The tokens it hands out are opaque tokens protected by Data Protection, not standard JWTs, so they only work against the same app. For tokens other services can validate, run a real identity provider instead (OpenID Connect).

Because users live in a database you also need migrations (dotnet ef migrations add Identity and dotnet ef database update; see Entity Framework Core Overview).

Password hashing

A site must never store passwords, or encrypted passwords. It stores a hash: the output of a one-way function that is slow on purpose. IPasswordHasher<TUser> does this for Identity. Its current format uses PBKDF2 (key derivation by repeated HMAC, here with SHA-512), a random salt per password so equal passwords give different hashes, and an iteration count that is stored inside the hash string itself. The stored string therefore says how it was made, which lets the framework spot an old hash after an upgrade and ask you to rehash it on the next successful login.

The next program is a stand-in with the same design, built from the base class library. It shows the three results that Identity's own PasswordVerificationResult has: failed, success, and success with rehash needed.

C# A PBKDF2 password hasher (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Study what the stored string contains: a version, the work factor, the salt and the derived key, everything needed to verify later and nothing that reveals the password. The cost is the point. At 100,000 iterations a single guess costs real time, so an attacker who steals the database cannot try billions of passwords per second. The work factor is a knob you raise as hardware gets faster, and the SuccessRehashNeeded result is the migration path.

Do not invent your own hash format for a real site. The example exists to explain Identity's hasher, which has been reviewed and tested far more than any copy. In a real project call UserManager.CreateAsync(user, password) and let Identity hash it.

Lockout, roles and two-factor codes

Password guessing is the simplest attack, so Identity counts failed attempts. With lockoutOnFailure: true in SignInManager.PasswordSignInAsync, the user is locked out after MaxFailedAccessAttempts failures (default 5) for DefaultLockoutTimeSpan (default 5 minutes). While locked, even the right password is refused, and a successful sign-in resets the counter. Note that lockout is not automatic: forgetting the lockoutOnFailure argument disables it for that sign-in call.

Two-factor authentication (2FA) adds a second proof after the password. The popular form is a time-based one-time password (TOTP), the six-digit code from an authenticator app. Both sides share a secret once (the QR code at setup time), then compute the same code from the secret and the current 30-second window. Identity implements this with UserManager.VerifyTwoFactorTokenAsync and a per-user authenticator key; it also stores single-use recovery codes for people who lose their phone.

The following stand-in combines these ideas: an in-memory user store with roles, lockout driven by a fake clock (so the output is the same every run) and a TOTP check following the RFC 6238 algorithm. The first line verifies the code generator against the official test vector from that RFC.

C# Lockout, roles and TOTP (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The sign-in flow in the output is the same decision tree the real SignInManager follows:

flowchart TD
    A["Password sign-in"] --> L{"Locked out?"}
    L -- "Yes" --> LO["LockedOut"]
    L -- "No" --> P{"Password correct?"}
    P -- "No" --> C{"Failures reached<br/>the maximum?"}
    C -- "Yes" --> LO
    C -- "No" --> F["Failed"]
    P -- "Yes" --> T{"2FA enabled?"}
    T -- "No" --> S["Success: issue cookie"]
    T -- "Yes" --> R["RequiresTwoFactor"]
    R --> V{"Code valid?"}
    V -- "Yes" --> S
    V -- "No" --> TF["Failed"]

Lockout is checked first so a locked account cannot be probed; two factors come only after the password is right.

A real authenticator app, Identity's GetAuthenticatorKeyAsync and a QR code library replace the shared secret and the hand-written Totp class. The algorithm, though, is exactly this small, which is why it works with any compliant app.

Passkeys and external logins

The best defense against password problems is to need fewer passwords.

Passkeys (WebAuthn/FIDO2) replace the password with a key pair held by the user's device or password manager: the server stores only a public key, and signing in means proving possession with a biometric or device PIN. A passkey cannot be phished and there is nothing secret in your database to steal. ASP.NET Core Identity in .NET 10 supports passkeys: SignInManager can sign a user in with a passkey and UserManager stores them, which requires the newer version 3 of the Identity database schema (a store option) and a store that implements the passkey interface. The Blazor Web App template with individual accounts includes the client-side script and pages to register and use passkeys. Browser-side WebAuthn cannot run in a server demo here, so treat this as a feature to switch on in a project rather than code to write by hand.

External logins delegate authentication to a provider such as Microsoft, Google, GitHub or any OpenID Connect server. Each provider is a package that adds one more scheme next to the cookie scheme:

C#
builder.Services.AddAuthentication()
    .AddGoogle(options =>
    {
        options.ClientId = builder.Configuration["Authentication:Google:ClientId"]!;
        options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"]!;
    });

When the user comes back from the provider, Identity links the external login to a local account (the AspNetUserLogins table) and signs them in with its own cookie. You still own the user record, roles and claims; the provider only vouches for who the person is. Keep the client secret in user secrets or a vault, never in source control (Environments and Secrets).

Should you use Identity?

Choose When
ASP.NET Core Identity You own the user database and want full control, within one application
An external identity provider (Entra ID, Auth0, Keycloak, Duende IdentityServer) Several apps share logins, you need single sign-on, or you do not want to run credential storage
Neither The only callers are services using API keys or tokens you issue by other means

Identity is a good default for a standalone web site or API with its own accounts. Whichever you choose, the application code stays the same: schemes produce principals, and policies decide what they can do. The last piece of the chapter is the set of habits and settings that protect all of it: Web Security Essentials.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a password hasher use a random salt per password?

    A unique salt means identical passwords produce different stored hashes and an attacker cannot reuse one precomputed table for the whole database. The salt is stored next to the hash; it is not secret.
  2. 2. What does the work factor (iteration count) stored inside a hash allow?

    Because the parameters travel with the hash, the verifier can tell that it was made with fewer iterations than the current setting and report success-with-rehash-needed.
  3. 3. Which statement about lockout in Identity is correct?

    PasswordSignInAsync counts failures toward lockout only when lockoutOnFailure is true. After the maximum failures the account is locked for the configured time span.
  4. 4. How does a TOTP authenticator code get verified by the server?

    TOTP (RFC 6238) derives a short code with HMAC from a secret shared at setup time and the current time step, so no network call to a code service is needed.
  5. 5. What does MapIdentityApi's login endpoint hand out by default?

    The Identity API endpoints issue proprietary bearer tokens protected with Data Protection. They are meant for clients of that one application, not for cross-service validation.

Summary

  • Identity is the membership system: UserManager and SignInManager on top of a pluggable store, usually EF Core.
  • Passwords are stored as slow, salted hashes with their parameters embedded, so they can be upgraded over time.
  • Lockout, role membership and two-factor codes are part of the sign-in flow; remember lockoutOnFailure.
  • TOTP is a small, standard algorithm over a shared secret and the time window.
  • .NET 10 adds passkey support; external providers plug in as extra authentication schemes.
  • After sign-in, a normal cookie and ClaimsPrincipal carry the identity, so policies work unchanged.

Next: Web Security Essentials