feat(auth): codes de récupération 2FA — 10 codes hashés à l'enrôlement, usage unique au login (Fixes #12)

This commit is contained in:
Arnaud Dartois committed 2026-08-11 21:35:52 +02:00
1 parent 9e64b03f31
commit 59a864bdfc
16 files changed
+2553 -9

No files matched your search

@@ -2,6 +2,7 @@ using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Application.Auth.Commands.Disable2fa;
@@ -9,11 +10,13 @@ namespace Heimdall.Application.Auth.Commands.Disable2fa;
public class Disable2faHandler : IRequestHandler<Disable2faCommand, ServiceResult>
{
private readonly UserManager<AppUser> _userManager;
private readonly IApplicationDbContext _db;
private readonly ILogger<Disable2faHandler> _logger;
public Disable2faHandler(UserManager<AppUser> userManager, ILogger<Disable2faHandler> logger)
public Disable2faHandler(UserManager<AppUser> userManager, IApplicationDbContext db, ILogger<Disable2faHandler> logger)
{
_userManager = userManager;
_db = db;
_logger = logger;
}
@@ -35,6 +38,17 @@ public class Disable2faHandler : IRequestHandler<Disable2faCommand, ServiceResul
return ServiceResult.Failure("Failed to disable 2FA");
}
// Purger les codes de récupération — ils ne sont plus valables
var codes = await _db.UserRecoveryCodes
.Where(r => r.UserId == request.UserId)
.ToListAsync(ct).ConfigureAwait(false);
if (codes.Count > 0)
{
_db.UserRecoveryCodes.RemoveRange(codes);
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
_logger.LogInformation("Disable2fa: Purged {Count} recovery codes UserId={UserId}", codes.Count, request.UserId);
}
_logger.LogInformation("Disable2fa: Disabled UserId={UserId}", request.UserId);
return ServiceResult.Success();
}
@@ -1,8 +1,10 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Auth.Services;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Application.Auth.Commands.Enable2fa;
@@ -10,11 +12,13 @@ namespace Heimdall.Application.Auth.Commands.Enable2fa;
public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult<Enable2faResponse>>
{
private readonly UserManager<AppUser> _userManager;
private readonly IApplicationDbContext _db;
private readonly ILogger<Enable2faHandler> _logger;
public Enable2faHandler(UserManager<AppUser> userManager, ILogger<Enable2faHandler> logger)
public Enable2faHandler(UserManager<AppUser> userManager, IApplicationDbContext db, ILogger<Enable2faHandler> logger)
{
_userManager = userManager;
_db = db;
_logger = logger;
}
@@ -46,8 +50,16 @@ public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult<
return ServiceResult<Enable2faResponse>.Failure("Failed to generate 2FA key");
}
// Générer 10 codes de récupération (P0 spec 4.3) — affichés UNE seule fois, stockés hashés
var recoveryCodes = RecoveryCodeService.Generate(10);
foreach (var code in recoveryCodes)
{
_db.UserRecoveryCodes.Add(new UserRecoveryCode(request.UserId, RecoveryCodeService.Hash(code)));
}
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
var qrCodeUri = $"otpauth://totp/Heimdall:{user.Email}?secret={key}&issuer=Heimdall&algorithm=SHA1&digits=6&period=30";
_logger.LogInformation("Enable2fa: Enabled UserId={UserId}", request.UserId);
return ServiceResult<Enable2faResponse>.Success(new Enable2faResponse(key, qrCodeUri));
_logger.LogInformation("Enable2fa: Enabled UserId={UserId} with {Count} recovery codes", request.UserId, recoveryCodes.Count);
return ServiceResult<Enable2faResponse>.Success(new Enable2faResponse(key, qrCodeUri, recoveryCodes, recoveryCodes.Count));
}
}
@@ -1,9 +1,11 @@
using Heimdall.Application.Auth.Services;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Application.Auth.Commands.Verify2fa;
@@ -13,17 +15,20 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
private readonly UserManager<AppUser> _userManager;
private readonly IJwtService _jwtService;
private readonly IRolePermissionService _rolePermissionService;
private readonly IApplicationDbContext _db;
private readonly ILogger<Verify2faHandler> _logger;
public Verify2faHandler(
UserManager<AppUser> userManager,
IJwtService jwtService,
IRolePermissionService rolePermissionService,
IApplicationDbContext db,
ILogger<Verify2faHandler> logger)
{
_userManager = userManager;
_jwtService = jwtService;
_rolePermissionService = rolePermissionService;
_db = db;
_logger = logger;
}
@@ -43,11 +48,35 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
if (!isValid)
{
_logger.LogWarning("Verify2fa: Invalid code Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
// TOTP invalide → tenter un code de récupération (usage unique)
var redeemed = await TryRedeemRecoveryCodeAsync(user, request.Code.Trim(), ct).ConfigureAwait(false);
if (!redeemed)
{
_logger.LogWarning("Verify2fa: Invalid code Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
}
_logger.LogInformation("Verify2fa: Recovery code redeemed Email={Email}", request.Email);
}
_logger.LogInformation("Verify2fa: Success Email={Email}", request.Email);
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
}
private async Task<bool> TryRedeemRecoveryCodeAsync(AppUser user, string code, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(code))
return false;
var codeHash = RecoveryCodeService.Hash(code);
var match = await _db.UserRecoveryCodes
.FirstOrDefaultAsync(r => r.UserId == user.Id && r.CodeHash == codeHash && r.UsedAt == null, ct)
.ConfigureAwait(false);
if (match is null)
return false;
match.MarkUsed();
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
return true;
}
}
@@ -0,0 +1,43 @@
using System.Security.Cryptography;
using System.Text;
namespace Heimdall.Application.Auth.Services;
/// <summary>
/// Generates and hashes 2FA recovery codes.
/// Codes are generated in a human-friendly grouped format and stored as SHA-256 hashes.
/// </summary>
public static class RecoveryCodeService
{
private const int CodeLength = 5;
private const string Alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // no I, O, 0, 1 to avoid confusion
/// <summary>Generate <paramref name="count"/> recovery codes in plain text (shown once to the user).</summary>
public static IReadOnlyList<string> Generate(int count = 10)
{
var codes = new List<string>(count);
for (var i = 0; i < count; i++)
{
codes.Add(GenerateSingle());
}
return codes;
}
/// <summary>SHA-256 hex hash of a recovery code (what is stored in the database).</summary>
public static string Hash(string code)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(code));
return Convert.ToHexString(bytes).ToLowerInvariant();
}
private static string GenerateSingle()
{
Span<char> chars = stackalloc char[CodeLength];
var bytes = RandomNumberGenerator.GetBytes(CodeLength);
for (var i = 0; i < CodeLength; i++)
{
chars[i] = Alphabet[bytes[i] % Alphabet.Length];
}
return new string(chars);
}
}
@@ -31,6 +31,7 @@ public interface IApplicationDbContext
DbSet<Site> Sites { get; }
DbSet<SiteCredential> SiteCredentials { get; }
DbSet<UserGroup> UserGroups { get; }
DbSet<UserRecoveryCode> UserRecoveryCodes { get; }
DbSet<UserSite> UserSites { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default);
+3 -1
View File
@@ -43,7 +43,9 @@ public record LogoutRequest(string RefreshToken);
public record Enable2faResponse(
string SharedKey,
string QrCodeUri);
string QrCodeUri,
IReadOnlyList<string>? RecoveryCodes = null,
int RecoveryCodesRemaining = 0);
public record ConfirmEmailRequest(string UserId, string Token);
public record ForgotPasswordRequest(string Email);
@@ -0,0 +1,28 @@
using Heimdall.Domain.Primitives;
namespace Heimdall.Domain.Entities;
/// <summary>
/// A single-use 2FA recovery code, stored hashed (SHA-256) — never in plain text.
/// 10 codes are generated at 2FA enrollment and shown to the user exactly once.
/// </summary>
public class UserRecoveryCode : Entity<Guid>
{
public Guid UserId { get; private set; }
public string CodeHash { get; private set; } = string.Empty;
public DateTime CreatedAt { get; private set; } = DateTime.UtcNow;
public DateTime? UsedAt { get; private set; }
private UserRecoveryCode() { } // EF Core
public UserRecoveryCode(Guid userId, string codeHash)
: base(Guid.NewGuid())
{
UserId = userId;
CodeHash = codeHash;
}
public bool IsUsed => UsedAt is not null;
public void MarkUsed() => UsedAt = DateTime.UtcNow;
}
@@ -57,6 +57,9 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicat
public DbSet<Person> Persons => Set<Person>();
public DbSet<KnownFace> KnownFaces => Set<KnownFace>();
// 2FA recovery codes (stored hashed)
public DbSet<UserRecoveryCode> UserRecoveryCodes => Set<UserRecoveryCode>();
public async Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default)
{
await DbContextExtensions.SaveChangesWithRetryAsync(this, maxRetries, ct).ConfigureAwait(false);
@@ -0,0 +1,34 @@
using Heimdall.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Heimdall.Infrastructure.Data.Configurations;
public class UserRecoveryCodeConfiguration : IEntityTypeConfiguration<UserRecoveryCode>
{
public void Configure(EntityTypeBuilder<UserRecoveryCode> builder)
{
builder.ToTable("user_recovery_codes");
builder.HasKey(r => r.Id);
builder.Property(r => r.CodeHash)
.HasMaxLength(64)
.IsRequired()
.IsUnicode(false);
builder.Property(r => r.UserId)
.IsRequired();
builder.Property(r => r.CreatedAt)
.HasDefaultValueSql("NOW()");
builder.Property(r => r.UsedAt);
// Indexes for lookup during login (single-use redemption)
builder.HasIndex(r => new { r.UserId, r.CodeHash })
.IsUnique();
builder.HasIndex(r => r.UserId);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,48 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Heimdall.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddUserRecoveryCodes : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "user_recovery_codes",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<Guid>(type: "uuid", nullable: false),
CodeHash = table.Column<string>(type: "character varying(64)", unicode: false, maxLength: 64, nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
UsedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_user_recovery_codes", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_user_recovery_codes_UserId",
table: "user_recovery_codes",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_user_recovery_codes_UserId_CodeHash",
table: "user_recovery_codes",
columns: new[] { "UserId", "CodeHash" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "user_recovery_codes");
}
}
}
@@ -1456,6 +1456,39 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("user_notification_configs", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserRecoveryCode", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CodeHash")
.IsRequired()
.HasMaxLength(64)
.IsUnicode(false)
.HasColumnType("character varying(64)");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<DateTime?>("UsedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("UserId", "CodeHash")
.IsUnique();
b.ToTable("user_recovery_codes", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b =>
{
b.Property<Guid>("UserId")
+141 -1
View File
@@ -1,6 +1,7 @@
@page "/profile"
@attribute [Authorize]
@layout MainLayout
@using Enable2faResponse = Heimdall.Application.DTOs.Enable2faResponse
@inject HeimdallApiClient Api
@inject AuthState Auth
@inject ISnackbar Snackbar
@@ -88,11 +89,27 @@ else if (_profile is not null)
</MudItem>
<MudItem xs="12" sm="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">2FA</MudText>
<MudText Typo="Typo.body1" Class="mb-3">
<MudText Typo="Typo.body1" Class="mb-1">
<MudIcon Icon="@(_profile.TwoFactorEnabled ? Icons.Material.Filled.CheckCircle : Icons.Material.Filled.Cancel)"
Color="@(_profile.TwoFactorEnabled ? Color.Success : Color.Default)" Size="Size.Small" />
@(_profile.TwoFactorEnabled ? "Activé" : "Désactivé")
</MudText>
@if (_profile.TwoFactorEnabled)
{
<MudButton Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small" Class="mt-1"
OnClick="Disable2fa" Disabled="@_toggling2fa">
@if (_toggling2fa) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
Désactiver la 2FA
</MudButton>
}
else
{
<MudButton Variant="Variant.Filled" Color="Color.Primary" Size="Size.Small" Class="mt-1"
OnClick="Enable2fa" Disabled="@_toggling2fa">
@if (_toggling2fa) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
Activer la 2FA
</MudButton>
}
</MudItem>
<MudItem xs="12" sm="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Rôles</MudText>
@@ -194,6 +211,66 @@ else if (_profile is not null)
</MudPaper>
}
@* ─── Dialog d'enrôlement 2FA (QR + codes de récupération) ─── *@
<MudOverlay Visible="@_show2faDialog" OnClick="@(() => _show2faDialog = false)" />
<MudDialog @bind-Visible="_show2faDialog" Options="new DialogOptions { MaxWidth = MaxWidth.Medium, FullWidth = true }">
<TitleContent>
<MudText Typo="Typo.h6">
<MudIcon Icon="@Icons.Material.Filled.Security" Class="mr-1" Size="Size.Small" />
Activer la double authentification (2FA)
</MudText>
</TitleContent>
<DialogContent>
@if (_2faError is not null)
{
<MudAlert Severity="Severity.Error" Class="mb-4">@_2faError</MudAlert>
}
else if (_2faSetup is not null)
{
<MudAlert Severity="Severity.Info" Variant="Variant.Outlined" Class="mb-4">
<MudText Typo="Typo.body2" Class="mb-1">
Scannez le code QR avec votre application d'authentification (Google Authenticator, Authy…)
ou saisissez la clé manuellement.
</MudText>
<MudText Typo="Typo.body2" Class="mb-1">
<strong>Clé :</strong> <code>@_2faSetup.SharedKey</code>
</MudText>
@if (!string.IsNullOrEmpty(_2faSetup.QrCodeUri))
{
<MudText Typo="Typo.caption" Color="Color.Secondary">
Lien de configuration : <a href="@_2faSetup.QrCodeUri" target="_blank">ouvrir dans l'app</a>
</MudText>
}
</MudAlert>
@if (_2faSetup.RecoveryCodes is { Count: > 0 })
{
<MudAlert Severity="Severity.Warning" Variant="Variant.Outlined" Class="mb-2">
<MudText Typo="Typo.body2" Class="mb-1">
<strong>Codes de récupération</strong> — conservez-les précieusement.
Ils permettent de vous connecter si vous perdez votre application d'authentification.
Chaque code ne peut être utilisé qu'une seule fois.
</MudText>
</MudAlert>
<MudPaper Elevation="0" Class="pa-3 mb-4" Style="border: 1px dashed #f0ad4e; border-radius: 8px;">
<div class="d-flex flex-wrap">
@foreach (var rc in _2faSetup.RecoveryCodes)
{
<MudText Typo="Typo.subtitle1" Class="d-inline mr-4 mb-2" Style="font-family: monospace;">
@rc
</MudText>
}
</div>
</MudPaper>
<MudCheckBox T="bool" @bind-Value="_recoveryCodesConfirmed" Label="J'ai sauvegardé mes codes de récupération" Class="mb-2" />
}
}
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@(() => _show2faDialog = false)">Fermer</MudButton>
</DialogActions>
</MudDialog>
@code {
private UserItem? _profile;
private bool _loading = true;
@@ -213,6 +290,13 @@ else if (_profile is not null)
private string _confirmPassword = "";
private string _passwordError = "";
// Section 2FA
private bool _toggling2fa;
private bool _show2faDialog;
private Enable2faResponse? _2faSetup;
private string? _2faError;
private bool _recoveryCodesConfirmed;
protected override async Task OnInitializedAsync()
{
await LoadProfile();
@@ -273,6 +357,62 @@ else if (_profile is not null)
// ─── Section 3: Changer le mot de passe ───────────────────────
private async Task Enable2fa()
{
_toggling2fa = true;
_2faError = null;
_2faSetup = null;
_recoveryCodesConfirmed = false;
try
{
var setup = await Api.Enable2faAsync();
if (setup is null)
{
_2faError = "Échec de l'activation de la 2FA. Réessayez.";
_show2faDialog = true;
return;
}
_2faSetup = setup;
_show2faDialog = true;
}
catch
{
_2faError = UiErrors.OperationFailed();
_show2faDialog = true;
}
finally
{
_toggling2fa = false;
await LoadProfile();
}
}
private async Task Disable2fa()
{
_toggling2fa = true;
try
{
var ok = await Api.Disable2faAsync();
if (ok)
{
Snackbar.Add("Double authentification désactivée", Severity.Success);
}
else
{
Snackbar.Add("Échec de la désactivation de la 2FA", Severity.Error);
}
}
catch
{
Snackbar.Add(UiErrors.OperationFailed(), Severity.Error);
}
finally
{
_toggling2fa = false;
await LoadProfile();
}
}
private async Task ChangePassword()
{
if (string.IsNullOrWhiteSpace(_currentPassword))
@@ -2,6 +2,7 @@ using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using Heimdall.Application.DTOs;
namespace Heimdall.Web.Services;
@@ -159,6 +160,21 @@ public class HeimdallApiClient
return result;
}
public async Task<Enable2faResponse?> Enable2faAsync()
{
var client = CreateClient();
var response = await client.PostAsync("api/auth/2fa/enable", null);
if (!response.IsSuccessStatusCode) return null;
return await response.Content.ReadFromJsonAsync<Enable2faResponse>(Json);
}
public async Task<bool> Disable2faAsync()
{
var client = CreateClient();
var response = await client.PostAsync("api/auth/2fa/disable", null);
return response.IsSuccessStatusCode;
}
/// <summary>
/// Stores the last successful auth response for use by the token refresh handler.
/// </summary>