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:
1 parent
940e826865
commit
7be5d42e85
16 files changed
+2102
-66
No files matched your search
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user