Lesson 6 of 8
Two-Factor Authentication (TOTP)
TOTP (Time-based One-Time Password, RFC 6238) is the algorithm behind Google Authenticator and Microsoft Authenticator. ASP.NET Core Identity has built-in support - you generate a shared secret, user scans it as a QR code, and then verifies 6-digit codes during login.
TOTP 2FA Setup Flow
// ━━ 2FA enrollment ━━
[HttpPost("2fa/setup"), Authorize]
public async Task<IActionResult> Setup2FA()
{
var user = await userManager.GetUserAsync(User)
?? throw new UnauthorizedAccessException();
// Generate authenticator key (base32-encoded secret)
await userManager.ResetAuthenticatorKeyAsync(user);
var key = await userManager.GetAuthenticatorKeyAsync(user);
// QR code data - user scans this with Google Authenticator
var appName = "MyApp";
var qrCodeUri = $"otpauth://totp/{Uri.EscapeDataString(appName)}:{Uri.EscapeDataString(user.Email!)}?secret={key}&issuer={Uri.EscapeDataString(appName)}&algorithm=SHA1&digits=6&period=30";
return Ok(new
{
SharedKey = FormatKey(key!), // formatted for manual entry
QrCodeUri = qrCodeUri, // pass to frontend QR code library
RecoveryCodesNote = "Will be provided after verification"
});
}
// ━━ Verify TOTP code and enable 2FA ━━
[HttpPost("2fa/verify"), Authorize]
public async Task<IActionResult> Verify2FA([FromBody] Verify2FARequest request)
{
var user = await userManager.GetUserAsync(User)!;
var isValid = await userManager.VerifyTwoFactorTokenAsync(
user!, userManager.Options.Tokens.AuthenticatorTokenProvider,
request.Code.Replace(" ", "").Replace("-", ""));
if (!isValid)
return BadRequest(new { error = "Invalid verification code" });
await userManager.SetTwoFactorEnabledAsync(user!, true);
// Generate recovery codes - show ONCE to user
var recoveryCodes = await userManager.GenerateNewTwoFactorRecoveryCodesAsync(user!, 10);
return Ok(new { message = "2FA enabled", recoveryCodes });
}
// ━━ Login with 2FA ━━
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequest request)
{
var user = await userManager.FindByEmailAsync(request.Email);
if (user is null || !await userManager.CheckPasswordAsync(user, request.Password))
return Unauthorized(new { error = "Invalid credentials" });
if (await userManager.GetTwoFactorEnabledAsync(user))
{
// 2FA required - return a challenge token (short-lived, encrypted)
var challengeToken = Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32));
// Store challengeToken → userId mapping with short expiry
return Ok(new { requires2FA = true, challengeToken });
}
// No 2FA - issue tokens directly
return await IssueTokensAsync(user);
}
[HttpPost("login/2fa")]
public async Task<IActionResult> Login2FA([FromBody] TwoFALoginRequest request)
{
// Validate challenge token → get userId
// Then verify TOTP:
var user = await userManager.FindByIdAsync(request.UserId);
var valid = await userManager.VerifyTwoFactorTokenAsync(
user!, userManager.Options.Tokens.AuthenticatorTokenProvider, request.Code);
if (!valid) return Unauthorized(new { error = "Invalid 2FA code" });
return await IssueTokensAsync(user!);
}
private static string FormatKey(string key) =>
string.Join("-", Enumerable.Range(0, key.Length / 4)
.Select(i => key.Substring(i * 4, Math.Min(4, key.Length - i * 4))));
private Task<IActionResult> IssueTokensAsync(ApplicationUser user) =>
Task.FromResult<IActionResult>(Ok("tokens"));
record Verify2FARequest(string Code);
record TwoFALoginRequest(string UserId, string Code);
record LoginRequest(string Email, string Password);
class ApplicationUser { public string Id { get; set; } = ""; public string? Email { get; set; } }
UserManager<ApplicationUser> userManager = null!;Tip
Tip
Practice TwoFactor Authentication TOTP in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of TwoFactor Authentication TOTP from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with TwoFactor Authentication TOTP is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?