fix(identity): DB refresh tokens, auto-refresh handler, 2FA endpoints, JWT fix

- DB-backed RevokedRefreshToken entity + migration (remplace ConcurrentDictionary\n  en memoire, fonctionne en multi-instance et survive aux redemarrages)\n- TokenRefreshHandler: auto-refresh des JWT 401 via DelegatingHandler\n  (avec SemaphoreSlim pour eviter les refresh storms)\n- Fix: GenerateRefreshToken genere maintenant un JWT valide au lieu de\n  bytes aleatoires (ValidateRefreshToken attendait un JWT - flux casse)\n- Fix: Login.razor gere Requires2fa correctement (affiche champ code 2FA)\n- Ajout: endpoints POST /api/auth/2fa/enable et /2fa/disable\n- Ajout: Disable2faAsync dans IAuthService\n- Fix: GenerateTemporaryPassword garantit les 4 categories de charactere\n  (uppercase, lowercase, digit, non-alphanumeric)\n- Fix: TestFactory ajoute Jwt:RefreshKey manquant\n\nBuild: 0 errors, 0 warnings\nTests: 226/226 passed
This commit is contained in:
Arnaud Dartois committed 2026-07-21 08:57:53 +00:00
1 parent 940e826865
commit 7be5d42e85
16 files changed
+2102 -66

No files matched your search

+94 -33
View File
@@ -19,22 +19,38 @@
</div>
<div class="auth-form">
<form @onsubmit="LoginAsync">
<MudTextField @bind-Value="_email"
Label="Email"
Variant="Variant.Outlined"
Class="mb-4"
Required="true"
Immediate="true"
Autocomplete="email" />
<MudTextField @bind-Value="_password"
Label="Mot de passe"
Variant="Variant.Outlined"
InputType="InputType.Password"
Class="mb-4"
Required="true"
Immediate="true"
Autocomplete="current-password" />
<form @onsubmit="HandleSubmitAsync">
@if (!_requires2fa)
{
<MudTextField @bind-Value="_email"
Label="Email"
Variant="Variant.Outlined"
Class="mb-4"
Required="true"
Immediate="true"
Autocomplete="email" />
<MudTextField @bind-Value="_password"
Label="Mot de passe"
Variant="Variant.Outlined"
InputType="InputType.Password"
Class="mb-4"
Required="true"
Immediate="true"
Autocomplete="current-password" />
}
else
{
<MudAlert Severity="Severity.Info" Class="mb-4">
Authentification à deux facteurs requise. Saisissez le code généré par votre application d'authentification.
</MudAlert>
<MudTextField @bind-Value="_twoFactorCode"
Label="Code 2FA"
Variant="Variant.Outlined"
Class="mb-4"
Required="true"
Immediate="true"
Autocomplete="one-time-code" />
}
<div class="auth-error">
@if (!string.IsNullOrEmpty(_errorMessage))
@@ -53,7 +69,7 @@
{
<MudProgressCircular Size="Size.Small" Class="mr-2" Color="Color.Inherit" />
}
@(_loading ? "Connexion en cours…" : "Se connecter")
@(_loading ? "Connexion en cours…" : (_requires2fa ? "Vérifier" : "Se connecter"))
</MudButton>
</form>
</div>
@@ -70,10 +86,15 @@
@code {
private string _email = "";
private string _password = "";
private string _twoFactorCode = "";
private bool _requires2fa;
private bool _loading;
private string _errorMessage = "";
private string _returnUrl = "/dashboard";
private Task HandleSubmitAsync() =>
_requires2fa ? Verify2faAsync() : LoginAsync();
protected override void OnInitialized()
{
if (Auth.IsLoggedIn)
@@ -103,26 +124,15 @@
return;
}
// Update Blazor-level auth state
await AuthStateProvider.NotifyLoginAsync(result);
// Create middleware-level auth cookie so the ASP.NET Core
// middleware recognizes the user on subsequent requests.
var cookieOk = true;
if (!string.IsNullOrEmpty(result.AccessToken))
// Check if 2FA is required
if (result.Requires2fa)
{
cookieOk = await AuthHelper.SignInAsync(JsRuntime,
AuthHelper.CreateSignInPayload(result.AccessToken));
}
if (!cookieOk)
{
_errorMessage = "Erreur lors de la création de la session. Veuillez réessayer.";
_requires2fa = true;
_loading = false;
return;
}
Snackbar.Add("Connexion réussie", Severity.Success);
Navigation.NavigateTo(_returnUrl);
await CompleteAuthAsync(result);
}
catch (Exception ex)
{
@@ -130,4 +140,55 @@
}
finally { _loading = false; }
}
private async Task Verify2faAsync()
{
if (string.IsNullOrWhiteSpace(_twoFactorCode))
{
_errorMessage = "Le code 2FA est requis";
return;
}
_loading = true;
_errorMessage = "";
try
{
var result = await Api.Verify2faAsync(_email, _twoFactorCode.Trim());
if (result is null)
{
_errorMessage = "Code 2FA invalide. Veuillez réessayer.";
return;
}
await CompleteAuthAsync(result);
}
catch (Exception ex)
{
_errorMessage = $"Erreur : {ex.Message}";
}
finally { _loading = false; }
}
private async Task CompleteAuthAsync(AuthResponse result)
{
// Update Blazor-level auth state
await AuthStateProvider.NotifyLoginAsync(result);
// Create middleware-level auth cookie
var cookieOk = true;
if (!string.IsNullOrEmpty(result.AccessToken))
{
cookieOk = await AuthHelper.SignInAsync(JsRuntime,
AuthHelper.CreateSignInPayload(result.AccessToken));
}
if (!cookieOk)
{
_errorMessage = "Erreur lors de la création de la session. Veuillez réessayer.";
return;
}
Snackbar.Add("Connexion réussie", Severity.Success);
Navigation.NavigateTo(_returnUrl);
}
}
@@ -112,6 +112,40 @@ public class AuthController : ControllerBase
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Enable 2FA for the current user.</summary>
[Authorize]
[HttpPost("2fa/enable")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Enable2fa(CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
return Unauthorized(new { error = "Invalid user identity" });
var result = await _authService.Enable2faAsync(userId, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Disable 2FA for the current user.</summary>
[Authorize]
[HttpPost("2fa/disable")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Disable2fa(CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
return Unauthorized(new { error = "Invalid user identity" });
var result = await _authService.Disable2faAsync(userId, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Logout — revoke the current refresh token.</summary>
[Authorize]
[HttpPost("logout")]
+4 -2
View File
@@ -214,8 +214,9 @@ if (hangfireEnabled)
builder.Services.AddScoped<AgentFailoverJob>();
}
// ── HTTP client for Heimdall API ──────────────────────────────────
// ── HTTP client for Heimdall API (with auto-refresh handler) ──────
builder.Services.AddScoped<HeimdallApiClient>();
builder.Services.AddTransient<TokenRefreshHandler>();
var apiBaseUrl = builder.Configuration.GetValue<string>("ApiBaseUrl")
?? Environment.GetEnvironmentVariable("API_BASE_URL")
?? "http://localhost:8080";
@@ -223,7 +224,8 @@ builder.Services.AddHttpClient("HeimdallApi", client =>
{
client.BaseAddress = new Uri(apiBaseUrl.TrimEnd('/') + "/");
client.Timeout = TimeSpan.FromSeconds(30);
});
})
.AddHttpMessageHandler<TokenRefreshHandler>();
// Auth state (shared between services and components)
builder.Services.AddScoped<AuthState>();
+21 -2
View File
@@ -133,7 +133,9 @@ public class HeimdallApiClient
var client = CreateClient();
var response = await client.PostAsJsonAsync("api/auth/login", new { email, password });
if (!response.IsSuccessStatusCode) return null;
return await response.Content.ReadFromJsonAsync<AuthResponse>(Json);
var result = await response.Content.ReadFromJsonAsync<AuthResponse>(Json);
if (result is not null) _lastAuthResponse = result;
return result;
}
public async Task<AuthResponse?> RegisterAsync(string email, string password, string displayName)
@@ -142,9 +144,26 @@ public class HeimdallApiClient
var response = await client.PostAsJsonAsync("api/auth/register",
new { email, password, displayName });
if (!response.IsSuccessStatusCode) return null;
return await response.Content.ReadFromJsonAsync<AuthResponse>(Json);
var result = await response.Content.ReadFromJsonAsync<AuthResponse>(Json);
if (result is not null) _lastAuthResponse = result;
return result;
}
public async Task<AuthResponse?> Verify2faAsync(string email, string code)
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("api/auth/2fa/verify", new { email, code });
if (!response.IsSuccessStatusCode) return null;
var result = await response.Content.ReadFromJsonAsync<AuthResponse>(Json);
if (result is not null) _lastAuthResponse = result;
return result;
}
/// <summary>
/// Stores the last successful auth response for use by the token refresh handler.
/// </summary>
internal AuthResponse? _lastAuthResponse;
// ─── Users ────────────────────────────────────────────────────
public async Task<PagedData<UserItem>?> GetUsersAsync(int page = 1, int pageSize = 20)
@@ -0,0 +1,132 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
namespace Heimdall.Web.Services;
/// <summary>
/// DelegatingHandler that intercepts 401 responses and automatically tries
/// to refresh the access token using the stored refresh token.
/// If refresh fails, the user is logged out.
/// </summary>
public class TokenRefreshHandler : DelegatingHandler
{
private readonly AuthState _authState;
private readonly HeimdallAuthStateProvider _authStateProvider;
private readonly string _apiBaseUrl;
private static readonly JsonSerializerOptions Json = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
/// <summary>Prevents concurrent refresh storms when multiple requests fail at once.</summary>
private static readonly SemaphoreSlim _refreshLock = new(1, 1);
public TokenRefreshHandler(
AuthState authState,
HeimdallAuthStateProvider authStateProvider,
IConfiguration configuration)
{
_authState = authState;
_authStateProvider = authStateProvider;
_apiBaseUrl = configuration.GetValue<string>("ApiBaseUrl")
?? Environment.GetEnvironmentVariable("API_BASE_URL")
?? "http://localhost:8080";
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
// Clone the request so we can retry it
var response = await base.SendAsync(request, cancellationToken);
// Only intercept 401 responses for the Heimdall API
if (response.StatusCode != System.Net.HttpStatusCode.Unauthorized
|| request.RequestUri?.LocalPath.StartsWith("/api/auth/", StringComparison.Ordinal) == true)
{
return response;
}
// Try to refresh the token
var refreshed = await TryRefreshTokenAsync(cancellationToken);
if (!refreshed)
{
// Refresh failed — logout user
await _authStateProvider.NotifyLogoutAsync();
return response;
}
// Retry the original request with the new access token
var retryRequest = await CloneHttpRequestMessageAsync(request);
retryRequest.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", _authState.AccessToken);
response.Dispose();
return await base.SendAsync(retryRequest, cancellationToken);
}
private async Task<bool> TryRefreshTokenAsync(CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(_authState.RefreshToken))
return false;
await _refreshLock.WaitAsync(cancellationToken);
try
{
// Double-check: another thread might have refreshed already
if (!string.IsNullOrEmpty(_authState.AccessToken))
return true;
// Create a raw HttpClient (NOT the "HeimdallApi" named client which
// includes this handler — would cause an infinite loop).
using var rawClient = new HttpClient { BaseAddress = new Uri(_apiBaseUrl.TrimEnd('/') + "/") };
var response = await rawClient.PostAsJsonAsync(
"api/auth/refresh",
new { refreshToken = _authState.RefreshToken },
cancellationToken);
if (!response.IsSuccessStatusCode)
return false;
var result = await response.Content
.ReadFromJsonAsync<AuthResponse>(Json, cancellationToken);
if (result is null || string.IsNullOrEmpty(result.AccessToken))
return false;
// Update auth state with the new tokens
await _authStateProvider.NotifyLoginAsync(result);
return true;
}
catch
{
return false;
}
finally
{
_refreshLock.Release();
}
}
private static async Task<HttpRequestMessage> CloneHttpRequestMessageAsync(HttpRequestMessage request)
{
var clone = new HttpRequestMessage(request.Method, request.RequestUri);
if (request.Content is not null)
{
var contentBytes = await request.Content.ReadAsByteArrayAsync();
clone.Content = new ByteArrayContent(contentBytes);
if (request.Content.Headers.ContentType is not null)
clone.Content.Headers.ContentType = request.Content.Headers.ContentType;
}
foreach (var (key, value) in request.Headers)
clone.Headers.TryAddWithoutValidation(key, value);
foreach (var (key, value) in request.Options)
clone.Options.TryAdd(key, value);
return clone;
}
}