受欢迎的博客标签

 C# ASP.NET Core 项目使用Microsoft.AspNetCore.Identity内置 2FA 验证

Published

 C# 里实现 Authenticator App(如 Google Authenticator / Microsoft Authenticator)的 2FA 验证,本质是实现 TOTP(Time-based One-Time Password,RFC 6238)

使用成熟库Otp.NET

示例(生成 + 验证)

using OtpNet;
using QRCoder;
using System;
using System.Text;

class Program
{
    static void Main()
    {
        // 1️⃣ 生成密钥(用户注册时生成一次)
        var secretKey = KeyGeneration.GenerateRandomKey(20);
        var base32Secret = Base32Encoding.ToString(secretKey);

        Console.WriteLine("Secret (保存到数据库):");
        Console.WriteLine(base32Secret);

        // 2️⃣ 生成 TOTP
        var totp = new Totp(secretKey);
        var code = totp.ComputeTotp();

        Console.WriteLine("当前验证码:");
        Console.WriteLine(code);

        // 3️⃣ 验证用户输入
        Console.WriteLine("请输入验证码:");
        var input = Console.ReadLine();

        bool isValid = totp.VerifyTotp(input, out long timeStepMatched, VerificationWindow.RfcSpecifiedNetworkDelay);

        Console.WriteLine(isValid ? "验证成功" : "验证失败");
    }
}

ASP.NET Core 项目,直接使用Microsoft.AspNetCore.Identity,内置 2FA 支持