Bitzsoft.Integrations.MFA 1.0.0-alpha.7

This is a prerelease version of Bitzsoft.Integrations.MFA.
dotnet add package Bitzsoft.Integrations.MFA --version 1.0.0-alpha.7
                    
NuGet\Install-Package Bitzsoft.Integrations.MFA -Version 1.0.0-alpha.7
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Bitzsoft.Integrations.MFA" Version="1.0.0-alpha.7" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Bitzsoft.Integrations.MFA" Version="1.0.0-alpha.7" />
                    
Directory.Packages.props
<PackageReference Include="Bitzsoft.Integrations.MFA" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Bitzsoft.Integrations.MFA --version 1.0.0-alpha.7
                    
#r "nuget: Bitzsoft.Integrations.MFA, 1.0.0-alpha.7"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Bitzsoft.Integrations.MFA@1.0.0-alpha.7
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Bitzsoft.Integrations.MFA&version=1.0.0-alpha.7&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Bitzsoft.Integrations.MFA&version=1.0.0-alpha.7&prerelease
                    
Install as a Cake Tool

Bitzsoft.Integrations.MFA

企业级多因素认证(MFA)集成包 — TOTP、Email/SMS 验证码、FIDO2/WebAuthn、恢复码、策略引擎、受信设备、审计日志。

功能特性

  • TOTP 时间密码:基于 Otp.NET 的 TOTP 生成/验证,QR 码一键扫描
  • Email/SMS 验证码:通过 Provider 抽象接入任意邮件/短信服务商
  • FIDO2/WebAuthn:硬件密钥注册/验证,克隆检测,最后一凭据降级保护
  • 恢复码:HMAC-SHA256 单向哈希存储,一次性使用后自动消耗
  • 策略引擎:用户级 > 角色级 > 全局级三级策略,缓存加速
  • 受信设备:服务端生成 GUID 令牌,通过 HttpOnly Cookie 管理
  • 审计日志:标准分页查询,记录所有 MFA 操作
  • 统一门面IMfaCoordinator 一键接入策略 + 验证 + 日志

安装

.NET CLI

dotnet add package Bitzsoft.Integrations.MFA

PackageReference

<PackageReference Include="Bitzsoft.Integrations.MFA" Version="1.0.0" />

配置

appsettings.json

{
  "MFA": {
    "Enabled": true,
    "TotpIssuer": "MyApp",
    "TotpStepSeconds": 30,
    "TotpDigits": 6,
    "EmailCodeExpirationMinutes": 5,
    "SmsCodeExpirationMinutes": 5,
    "EnableFido2": true,
    "Fido2RpId": "example.com",
    "Fido2RpName": "My App",
    "MaxFailedAttempts": 5,
    "LockoutMinutes": 15,
    "TrustedDeviceDays": 30,
    "AesKey": "base64-encoded-256-bit-key",
    "RecoveryCodeHashKey": "base64-encoded-256-bit-key"
  }
}
配置项 说明 默认值
Enabled 是否启用 MFA false
TotpIssuer TOTP 签发者名称(显示在 Authenticator App) Bitzsoft
TotpStepSeconds TOTP 时间步长(秒) 30
TotpDigits TOTP 验证码位数 6
TotpWindowOffset TOTP 窗口偏移量 1
EmailCodeExpirationMinutes Email 验证码过期时间(分钟) 5
EmailSendIntervalSeconds Email 验证码发送间隔(秒) 60
SmsCodeExpirationMinutes SMS 验证码过期时间(分钟) 5
SmsSendIntervalSeconds SMS 验证码发送间隔(秒) 60
EnableFido2 是否启用 FIDO2/WebAuthn true
Fido2RpId FIDO2 Relying Party ID(域名) --
Fido2RpName FIDO2 显示名称 --
AllowRecoveryCodes 是否允许使用恢复码 true
RecoveryCodeCount 恢复码生成数量 8
MaxFailedAttempts 最大失败尝试次数 5
LockoutMinutes 账户锁定时长(分钟) 15
TrustedDeviceDays 受信设备有效天数 30
MaxTrustedDevicesPerUser 每用户最大受信设备数 10
AesKey AES-256-GCM 密钥(Base64,用于 TOTP Secret 加密) --
RecoveryCodeHashKey HMAC-SHA256 密钥(Base64,用于恢复码哈希) --

注册服务

核心注册(必选)

using Bitzsoft.Integrations.MFA.DependencyInjection;

services.AddBitzsoftMFA(options =>
{
    options.Enabled = true;
    options.TotpIssuer = "MyApp";
    options.Fido2RpId = "example.com";
    options.AesKey = "your-base64-encoded-256-bit-key";
    options.RecoveryCodeHashKey = "your-base64-encoded-256-bit-key";
});

// 或从 IConfiguration 绑定
services.AddBitzsoftMFA(configuration.GetSection("MFA").Bind);

注册 Provider(必选)

services.AddBitzsoftMFA(options => { /* ... */ })
    .WithCacheProvider<RedisCacheProvider>()
    .WithSmsProvider<AliyunSmsProvider>()
    .WithEmailProvider<SmtpEmailProvider>();
Provider 说明 是否必须
ICacheProvider 缓存(验证码、频率限制、FIDO2 challenge)
ISmsOtpProvider SMS 发送 使用 SMS MFA 时必须
IEmailOtpProvider Email 发送 使用 Email MFA 时必须
IEncryptionProvider 对称加密(默认内置 AES-256-GCM) 否(可替换)
IRecoveryCodeHasher 恢复码哈希(默认内置 HMAC-SHA256) 否(可替换)

注册 Repository(必选)

services.AddScoped<IUserMfaConfigRepository, SqlUserMfaConfigRepository>();
services.AddScoped<IMfaPolicyRepository, SqlMfaPolicyRepository>();
services.AddScoped<IFido2CredentialRepository, SqlFido2CredentialRepository>();
services.AddScoped<ITrustedDeviceRepository, SqlTrustedDeviceRepository>();
services.AddScoped<IMfaLogRepository, SqlMfaLogRepository>();

使用示例

TOTP 设置

public class MfaController : ControllerBase
{
    private readonly ITotpService _totpService;

    [HttpPost("setup")]
    public async Task<IActionResult> SetupTotp(string userId, string email)
    {
        var setup = _totpService.GenerateSetup(userId, email);
        // 将 setup.QrCodeImage 返回给前端显示 QR 码
        // 将 setup.SecretKey 和 setup.RecoveryCodes 临时存储
        return Ok(new { qrCode = Convert.ToBase64String(setup.QrCodeImage), recoveryCodes = setup.RecoveryCodes });
    }

    [HttpPost("complete-setup")]
    public async Task<IActionResult> CompleteSetup(string userId, string code, string secret, List<string> recoveryCodes)
    {
        await _totpService.CompleteSetupAsync(userId, code, secret, recoveryCodes);
        return Ok();
    }
}

统一验证(推荐通过 IMfaCoordinator)

public class MfaController : ControllerBase
{
    private readonly IMfaCoordinator _coordinator;

    [HttpPost("verify")]
    public async Task<IActionResult> Verify(string userId, string code, MFAType mfaType)
    {
        var context = new MFAVerificationContext
        {
            TenantId = "tenant-1",
            ClientIP = HttpContext.Connection.RemoteIpAddress?.ToString(),
            UserAgent = Request.Headers.UserAgent
        };

        var result = await _coordinator.VerifyAsync(userId, code, mfaType, context);

        if (result.IsLocked)
            return StatusCode(423, new { lockedUntil = result.LockedUntil });

        if (!result.IsSuccess)
            return Unauthorized(new { reason = result.FailReason });

        return Ok(new { remainingCodes = result.RemainingRecoveryCodes });
    }

    [HttpGet("check")]
    public async Task<IActionResult> CheckRequired(string userId, [FromCookie] string? deviceToken)
    {
        var policy = await _coordinator.CheckMfaRequiredAsync(userId, deviceToken);
        return Ok(new { requiresMFA = policy.RequiresMFA, allowedMethods = policy.AllowedMethods });
    }
}

受信设备

[HttpPost("trust-device")]
public async Task<IActionResult> TrustDevice(string userId)
{
    var deviceToken = await _trustedDeviceService.TrustDeviceAsync(
        userId,
        deviceName: Request.Headers.UserAgent,
        clientIP: HttpContext.Connection.RemoteIpAddress?.ToString());

    Response.Cookies.Append("mfa_device_token", deviceToken, new CookieOptions
    {
        HttpOnly = true,
        Secure = true,
        SameSite = SameSiteMode.Strict,
        Expires = DateTimeOffset.UtcNow.AddDays(30)
    });

    return Ok();
}

核心类型一览

类型 说明
IMfaCoordinator 统一门面(策略 + 验证 + 受信设备 + 日志)
IMfaVerifyService 统一验证服务(根据 MFAType 路由)
ITotpService TOTP 生成/验证服务
IEmailMfaService Email 验证码发送/验证
ISmsMfaService SMS 验证码发送/验证
IFido2Service FIDO2/WebAuthn 注册/验证
IRecoveryCodeService 恢复码生成/验证/重新生成
IMfaPolicyService 三级策略评估服务
ITrustedDeviceService 受信设备管理
IMfaLogService 审计日志
ICacheProvider 缓存提供器(宿主实现)
IEncryptionProvider 对称加密提供器(内置 AES-256-GCM)

依赖

  • Microsoft.Extensions.Http — IHttpClientFactory
  • Microsoft.Extensions.Options — 选项模式
  • Microsoft.Extensions.Logging.Abstractions — 日志抽象
  • Otp.NET — TOTP 算法实现
  • QRCoder — QR 码生成
  • Fido2 — FIDO2/WebAuthn 协议实现

相关包

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0-alpha.7 52 6/16/2026
1.0.0-alpha.6 53 6/16/2026
1.0.0-alpha.5 49 6/14/2026
1.0.0-alpha.3 56 6/7/2026