Course contentsShow
← C#
Lesson 1180 of 1,90811. Identity, Security, and ClaimsFree lesson

Handling Two-Factor Authentication

Enforce multi-factor security requirements using TOTP or email-based verification codes.

In this lesson, you will learn how to implement Two-Factor Authentication (2FA) in ASP.NET Core Identity to add an extra layer of security beyond just a username and password.

Beyond the Password

When a user provides their password, they prove "something they know." 2FA introduces "something they have," such as a mobile device generating a Time-based One-Time Password (TOTP) or an email client receiving a verification code. In ASP.NET Core Identity, this is managed by the SignInManager<TUser> class, which tracks whether a user has a "Two-Factor" claim associated with their login session.

The TOTP Workflow

The most common implementation uses TOTP (like Google Authenticator). The process involves two main steps:

  1. Enrollment: The server generates a secret key for the user, which is stored in the database. The user scans a QR code generated from this key.
  2. Verification: During login, if the user has 2FA enabled, the SignInManager will return a SignInResult with RequiresTwoFactor = true. You then redirect the user to a page to input their code, which you validate using the UserManager.
// Inside your login controller
var result = await _signInManager.PasswordSignInAsync(user, password, false, lockoutOnFailure: true);

if (result.RequiresTwoFactor)
{
    return RedirectToAction("VerifyCode");
}

// In the VerifyCode action
var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(code, isPersistent: false, rememberClient: false);
if (result.Succeeded) 
{
    return LocalRedirect(returnUrl);
}

Why It Matters

Even if an attacker steals a user's password, 2FA prevents unauthorized access because the attacker lacks the physical device or email access required to generate the second factor. When designing this flow, always ensure that you provide "Recovery Codes" during the enrollment phase. These codes allow users to regain access if they lose their device, preventing them from being permanently locked out of their accounts.

Key Takeaway: 2FA significantly hardens your security by requiring a secondary verification step via TOTP or email once the initial password check succeeds, effectively mitigating the risk of credential theft.