As cyberattacks become more sophisticated, relying solely on passwords for authentication is no longer sufficient. Multi-Factor Authentication (MFA) adds an extra layer of security by requiring users to provide additional verification factors beyond just a password. ASP.NET Core Identity provides built-in support for implementing MFA using email, SMS, and authenticator apps (like Microsoft Authenticator or Google Authenticator).
In this article, we’ll explore how to set up and implement MFA in ASP.NET Core applications, along with best practices for securing user accounts.
What is Multi-Factor Authentication (MFA)?
MFA requires users to verify their identity using at least two of the following factors:
Something you know – Password or PIN
Something you have – Mobile phone, authenticator app, security key
Something you are – Biometric factors like fingerprint or facial recognition
Example: A user enters their password (factor 1) and then confirms a code sent via SMS or an authenticator app (factor 2).
Why Use MFA?
Protects against credential theft and phishing attacks
Reduces risk of account takeover
Provides compliance with industry standards (GDPR, HIPAA, PCI-DSS)
Setting Up ASP.NET Core Identity with MFA
Step 1. Configure Identity in Program.cs
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.SignIn.RequireConfirmedEmail = true;
options.Tokens.AuthenticatorTokenProvider = TokenOptions.DefaultAuthenticatorProvider;
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(10);
options.Password.RequiredLength = 8;
options.Password.RequireDigit = true;
options.Password.RequireUppercase = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
Step 2. Enable Two-Factor Authentication in User Profile
ASP.NET Core Identity has built-in APIs to manage 2FA.
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public ManageController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
[HttpGet]
public async Task<IActionResult> Enable2FA()
{
var user = await _userManager.GetUserAsync(User);
var is2faEnabled = await _userManager.GetTwoFactorEnabledAsync(user);
return View(new Enable2FAViewModel { Is2FAEnabled = is2faEnabled });
}
[HttpPost]
public async Task<IActionResult> Enable2FA(bool enable)
{
var user = await _userManager.GetUserAsync(User);
await _userManager.SetTwoFactorEnabledAsync(user, enable);
return RedirectToAction("Index", "Home");
}
}
Join the conversation! Your thoughts help the community grow.