skip to content

In ASP.NET Core Identity, how do e-mail confirmation and password-reset tokens work, and why does changing a user's security stamp invalidate those tokens and signed-in cookies?

level: seniorimportance: should knowfreq 38%

answer

  1. AddDefaultTokenProviders registers four
  2. the "Default" provider uses Data Protection
  3. TokenLifespan defaults to one day
  4. purpose, user id and stamp inside
  5. ValidationInterval defaults to 30 minutes

basics

~20 s

AddDefaultTokenProviders registers DataProtectorTokenProvider as the Default provider: tokens embed time, user id, purpose and security stamp, expire after one day and are not stored. Changing the stamp fails those tokens, and SecurityStampValidator rejects old cookies within 30 minutes.

solid answer

~40 s

`AddDefaultTokenProviders()` registers four providers: `Default` (`DataProtectorTokenProvider<TUser>`), `Email`, `Phone` and `Authenticator`. `TokenOptions` points `EmailConfirmationTokenProvider` and `PasswordResetTokenProvider` at `Default`. `GenerateEmailConfirmationTokenAsync` and `GeneratePasswordResetTokenAsync` return a Data Protection–protected blob holding the creation time, user id, a purpose string and the user's **security stamp**; nothing is stored server-side. `ConfirmEmailAsync` and `ResetPasswordAsync` unprotect it and check the `TokenLifespan` (default one day), user, purpose and stamp. The security stamp is a random value that `UserManager` regenerates on password changes and resets, and on `UpdateSecurityStampAsync`; any older token then fails. The `Identity.Application` cookie carries the stamp too, and `SecurityStampValidator` re-checks it every `ValidationInterval` (default 30 minutes), signing the user out on a mismatch.

code

csharp · 13 lines
csharp
var token = await users.GenerateEmailConfirmationTokenAsync(member);
var code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(token));
var link = $"https://plots.example.org/account/confirm?userId={member.Id}&code={code}";

// later, in the confirm endpoint
var decoded = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
var result = await users.ConfirmEmailAsync(member, decoded);

// shorten reset and confirmation links, and stamp checks
builder.Services.Configure<DataProtectionTokenProviderOptions>(o =>
    o.TokenLifespan = TimeSpan.FromHours(3));
builder.Services.Configure<SecurityStampValidatorOptions>(o =>
    o.ValidationInterval = TimeSpan.FromMinutes(5));

go deeper

for a junior

Recall the calls: GenerateEmailConfirmationTokenAsync with ConfirmEmailAsync, GeneratePasswordResetTokenAsync with ResetPasswordAsync, and that AddDefaultTokenProviders is required.

for a middle

Explain what the Default provider puts in a token, the one-day TokenLifespan, URL-encoding the token, and the purpose and stamp checks.

for a senior

Use the security stamp deliberately: tokens that die on credential change, the 30-minute ValidationInterval for cookies, and the shared Data Protection keys a farm needs.

for a principal

Weigh revocation latency against database load when choosing ValidationInterval, and decide which events must rotate the stamp.

## Token providers A **token provider** in ASP.NET Core Identity is an `IUserTwoFactorTokenProvider<TUser>` registered under a name. `UserManager` asks a named provider to generate or validate a token for a **purpose**. `AddDefaultTokenProviders()` registers four: | Name (`TokenOptions` constant) | Class | Used for | |---|---|---| | `Default` | `DataProtectorTokenProvider<TUser>` | e-mail confirmation, password reset, change e-mail | | `Email` | `EmailTokenProvider<TUser>` | short codes sent by e-mail for two-factor | | `Phone` | `PhoneNumberTokenProvider<TUser>` | change-phone and SMS codes | | `Authenticator` | `AuthenticatorTokenProvider<TUser>` | authenticator-app codes | `TokenOptions.EmailConfirmationTokenProvider`, `PasswordResetTokenProvider` and `ChangeEmailTokenProvider` all default to `Default`. Without `AddDefaultTokenProviders` (for example with plain `AddIdentity` or `AddIdentityCore`) the calls throw `NotSupportedException`: "No IUserTwoFactorTokenProvider<TUser> named 'Default' is registered." ## What a confirmation token contains For the community-garden site, a new member must confirm their e-mail before booking: 1. `UserManager.GenerateEmailConfirmationTokenAsync(user)` asks the `Default` provider. 2. `DataProtectorTokenProvider` writes the current UTC time, the user id, the purpose (`"EmailConfirmation"`) and the user's security stamp, then protects the bytes with an `IDataProtector` and Base64-encodes them. 3. The app puts the token in a link. Tokens contain characters that are unsafe in URLs, so encode them, for example with `WebEncoders.Base64UrlEncode`, and decode before validating; `MapIdentityApi` does this. 4. `ConfirmEmailAsync(user, token)` unprotects the token and checks, in order: not older than `TokenLifespan` (default **one day**, `DataProtectionTokenProviderOptions`), same user id, same purpose, same security stamp. Nothing is written to the database when the token is issued. Validity comes from the Data Protection keys and the stamp, so every instance must share Data Protection keys or links break across servers. ## The security stamp `IdentityUser.SecurityStamp` is a random string that represents "the current credentials". `UserManager` replaces it when a password is changed, reset, added or removed, and when you call `UpdateSecurityStampAsync(user)` (for example after revoking access). Effects: - **Outstanding tokens die.** A reset link issued before the change carries the old stamp and fails validation, so a reset link works once. - **Cookies are revalidated.** The `Identity.Application` cookie's principal includes the stamp. `AddIdentity` wires `SecurityStampValidator.ValidatePrincipalAsync` into the cookie's `OnValidatePrincipal`. Once the cookie is older than `SecurityStampValidatorOptions.ValidationInterval` (default **30 minutes**) it reloads the user; if the stamp differs it rejects the principal and signs the user out, otherwise it rebuilds the principal (picking up role or claim changes) and renews the cookie. So "sign out everywhere" in Identity is `UpdateSecurityStampAsync`, with up to 30 minutes of delay unless you lower `ValidationInterval`, which costs a database read per interval per user. ## Changing lifetimes - `services.Configure<DataProtectionTokenProviderOptions>(o => o.TokenLifespan = TimeSpan.FromHours(3))` changes every token from the `Default` provider. - To give confirmation links a longer life than reset links, register a second `DataProtectorTokenProvider` subclass with its own named options and point `TokenOptions.EmailConfirmationTokenProvider` at it. - `services.Configure<SecurityStampValidatorOptions>(o => o.ValidationInterval = TimeSpan.FromMinutes(5))` shortens the window after a stamp change. ## Why a valid-looking link says "Invalid token." `ConfirmEmailAsync` and `ResetPasswordAsync` report every token failure the same way, as an `IdentityError` with the code `InvalidToken`. The usual causes, in the order worth checking: 1. **Encoding.** The token was put in a URL without Base64url encoding, so `+` or `/` arrived altered. 2. **Wrong user.** The link's user id loads a different account from the one the token was issued for. 3. **Stamp changed.** The member changed their password, or an admin called `UpdateSecurityStampAsync`, after the link was sent. 4. **Too old.** More than `TokenLifespan` has passed. 5. **Different key ring.** Another instance, or a redeployed container without persisted Data Protection keys, cannot unprotect it. 6. **Wrong purpose.** A confirmation token was passed to `ResetPasswordAsync`, or the reverse; the provider compares purposes such as `EmailConfirmation` and `ResetPassword`.

  • After a password reset, why is the member still signed in on another device for a while?
    The reset changes the security stamp, but the other device's `Identity.Application` cookie is only compared with the database every `ValidationInterval`, 30 minutes by default. Until that check runs, the cookie is valid on its own. Lower the interval, or accept the delay.
  • Why do confirmation links fail after a deployment that added a second server?
    `DataProtectorTokenProvider` protects tokens with Data Protection. If each server has its own key ring, a token created on one cannot be unprotected on the other and validation fails. The servers must share persisted Data Protection keys and the same application name.

  • Password-reset tokens are stored in the AspNetUserTokens table and looked up on use.
  • A password-reset token stays valid until it is used, however old it is.
  • Changing the security stamp signs the user out of every device instantly.
  • AddIdentity registers the confirmation and reset token providers by itself.
  • The token returned by GenerateEmailConfirmationTokenAsync can be pasted into a URL unchanged.