TECHNICAL TUTORIAL

Authenticator App 2FA in ASP.NET Core.

Enable standards-based TOTP and recovery codes using ASP.NET Core Identity.

ASP.NET Core Identity TOTP

TOTP with ASP.NET Core Identity

1. Identity setup

Configure ASP.NET Core Identity and an authenticated account settings page.

2. Generate enrollment secret

var user = await userManager.GetUserAsync(User);
var key = await userManager.GetAuthenticatorKeyAsync(user);
if (string.IsNullOrEmpty(key))
{
    await userManager.ResetAuthenticatorKeyAsync(user);
    key = await userManager.GetAuthenticatorKeyAsync(user);
}

Generate an otpauth://totp/... URI with an encoded issuer, account name, and secret. Render it as a QR code using a trusted QR library. Never log the key.

3. Confirm enrollment

var valid = await userManager.VerifyTwoFactorTokenAsync(
    user, userManager.Options.Tokens.AuthenticatorTokenProvider, code.Replace(" ", ""));
if (!valid) return BadRequest("Invalid verification code");
await userManager.SetTwoFactorEnabledAsync(user, true);
var recoveryCodes = await userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);

Display recovery codes once over HTTPS. Require recent authentication for enrollment or disabling 2FA, add rate limits, and protect actions with anti-forgery validation.

4. Login

Use Identity SignInManager two-factor flows such as TwoFactorAuthenticatorSignInAsync after the password step. Do not implement custom TOTP comparisons without a compelling reason.