Introduction
TOTP (Time-based One-Time Password) is a secure two-factor authentication (2FA) method that generates temporary, single-use codes for user verification. These codes refresh at fixed intervals—usually every 30 seconds—and are synchronized with the current time. By dynamically changing the valid code, TOTP enhances security compared to static passwords, significantly reducing the risk of unauthorized access even if a code is intercepted, as it expires quickly.
This method ensures that each authentication attempt requires a fresh, time-sensitive code, making it a robust defense against replay attacks and credential theft. The process works by combining a shared secret key (known only to the server and the user) with the current time to generate a one-time password. This password is then used to verify the user's identity in addition to their regular login credentials. TOTP is widely used in various applications, such as securing online accounts, mobile banking, and more, due to its effectiveness in enhancing security without being overly complicated for users.
Why MFA?
Multi-Factor Authentication (MFA) significantly enhances application security by requiring users to verify their identity using multiple methods. While traditional authentication uses only a username and password, MFA adds a second layer — typically a time-based one-time password (TOTP), which expires every 30 seconds.
This article walks you through implementing TOTP-based MFA in a real-world ASP.NET Core setup consisting of,
- A Web API project to handle backend authentication logic.
- A MVC UI project to handle frontend interaction with the user.
Project Architecture
Our application consists of two projects.
totp_dotnet_api– ASP.NET Core Web API
- Contains TOTP Controller having login, setup and verify three endpoints.
- One TotpService class for logic handling
totp_dotnet_mvc– ASP.NET Core MVC
Contains login and setup TOTP pages with controller.
Folder Structure

Now let's create endpoints in the Web API project. The Web API project provides three key endpoints to manage user login and TOTP-based multi-factor authentication. Each of these plays a specific role in the authentication flow: login, MFA setup, and verification.

[HttpPost("login")]
public IActionResult Login([FromBody] LoginRequest request)
{
if (request == null)
return BadRequest("Invalid request");
var response = _totpService.Login(request.Username, request.Password);
return Ok(response);
}
[HttpPost("setup")]
public IActionResult SetupTotp([FromBody] TotpSetupRequest request)
{
if (request == null)
return BadRequest("Invalid request");
var response = _totpService.SetupTotp(request.Username);
return Ok(response);
}
[HttpPost("verify")]
public IActionResult VerifyTotp([FromBody] TotpVerificationRequest request)
{
if (request == null)
return BadRequest("Invalid request");
var response = _totpService.VerifyTotp(request.Username, request.Code);
return Ok(response);
}
In the code given above, we created endpoints for login, setup, and verification. Now lets create one TotpService.cs class inside Services folder as given in the folder structure. This class will contain different methods calling from controller. This service is responsible for all the logic behind.
- User login validation
- Setting up TOTP
- Verifying TOTP codes
In this example, there’s no real database — you're using static dictionaries (_userPasswords and _userSecrets) to simulate user data and their MFA secrets.
public class TotpService : ITotpService {
private readonly Dictionary<string, string> _userSecrets =
new Dictionary<string, string> {
{ "alice", "JBSWY3DPEHPK3PXP" }, // Example Base32 secret
{ "bob", "KRSXG5DSNBSWY3DP" },
{ "charlie", "MZXW6YTBOI======" }
};
private readonly Dictionary<string, string> _userPasswords =
new Dictionary<string, string> {
{ "alice", "password123" }, { "bob", "123456" }, { "charlie", "qwerty" }
};
public LoginResponse Login(string username, string password) {
// var key = KeyGeneration.GenerateRandomKey(20);
// var base32Secret = Base32Encoding.ToString(key);
_userSecrets.TryGetValue(username, out var base32Secret);
// In a real application, you would verify against a database
if (!_userPasswords.ContainsKey(username) ||
_userPasswords[username] != password) {
return new LoginResponse { Success = false,
Message = "Invalid credentials",
IsTotpEnabled = false, Secret = null };
}
// If TOTP is not enabled, show setup page
var setupResponse = SetupTotp(username);
var response = new LoginResponse {
Success = true, Message = "Login successful",
IsTotpEnabled = false, QrCodeUrl = setupResponse.QrCodeUrl,
Secret = base32Secret,
};
return response;
}
public LoginResponse SetupTotp(string username) {
_userSecrets.TryGetValue(username, out var base32Secret);
// Generate a random secret key
// var key = KeyGeneration.GenerateRandomKey(20);
// var base32Secret = Base32Encoding.ToString(key);
// Store the secret for the user
_userSecrets[username] = base32Secret;
return new LoginResponse {
Success = true, Message = "TOTP setup successful", IsTotpEnabled = true,
QrCodeUrl = GenerateQrCode(username, base32Secret), Secret = base32Secret
};
}
public TotpVerifyResponse VerifyTotp(string username, string code) {
if (!_userSecrets.TryGetValue(username, out var secret)) {
return new TotpVerifyResponse {
Success = false, Message = "TOTP not set up for this user"
};
}
var totp = new Totp(Base32Encoding.ToBytes(secret));
var isValid = totp.VerifyTotp(code, out _, new VerificationWindow(1, 1));
return new TotpVerifyResponse {
Success = isValid,
Message = isValid ? "TOTP verification successful" : "Invalid TOTP code"
};
}
private static string GenerateQrCode(string username, string secret) {
var issuer = "TotpPOC";
var qrCodeUrl =
$"otpauth://totp/{issuer}:{username}?secret={secret}&issuer={issuer}";
using var qrGenerator = new QRCodeGenerator();
var qrCodeData =
qrGenerator.CreateQrCode(qrCodeUrl, QRCodeGenerator.ECCLevel.Q);
using var qrCode = new PngByteQRCode(qrCodeData);
var qrCodeBytes = qrCode.GetGraphic(20);
using var mStream = new MemoryStream(qrCodeBytes);
var base64Image = Convert.ToBase64String(mStream.ToArray());
return $"data:image/png;base64,{base64Image}";
}
}



Join the conversation! Your thoughts help the community grow.