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

@@ -11,6 +11,7 @@ public interface IAuthService
Task<ServiceResult<AuthResponse>> RefreshTokenAsync(string refreshToken, CancellationToken ct);
Task<ServiceResult<AuthResponse>> RegisterAdminAsync(RegisterRequest request, CancellationToken ct);
Task<ServiceResult> Enable2faAsync(Guid userId, CancellationToken ct);
Task<ServiceResult> Disable2faAsync(Guid userId, CancellationToken ct);
Task<ServiceResult> ChangePasswordAsync(Guid userId, string currentPassword, string newPassword, CancellationToken ct);
Task LogoutAsync(Guid userId, string refreshToken, CancellationToken ct);
}
@@ -0,0 +1,33 @@
namespace Heimdall.Domain.Entities;
/// <summary>
/// Persisted store for revoked refresh tokens.
/// Replaces the in-memory ConcurrentDictionary in AuthService so that
/// blacklisted tokens survive server restarts and work in multi-instance deployments.
/// A background cleanup job should periodically purge expired entries.
/// </summary>
public class RevokedRefreshToken
{
public Guid Id { get; private set; } = Guid.NewGuid();
/// <summary>SHA256 hash of the revoked refresh token.</summary>
public string TokenHash { get; private set; } = string.Empty;
/// <summary>The user who owned this token.</summary>
public Guid UserId { get; private set; }
public DateTime RevokedAt { get; private set; } = DateTime.UtcNow;
/// <summary>When the refresh token would have expired naturally.
/// Used for cleanup — entries older than this can be purged.</summary>
public DateTime ExpiresAt { get; private set; }
private RevokedRefreshToken() { } // EF Core
public RevokedRefreshToken(string tokenHash, Guid userId, DateTime expiresAt)
{
TokenHash = tokenHash;
UserId = userId;
ExpiresAt = expiresAt;
}
}
@@ -42,6 +42,9 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>
// Event entities
public DbSet<CameraEvent> CameraEvents => Set<CameraEvent>();
// Security entities
public DbSet<RevokedRefreshToken> RevokedRefreshTokens => Set<RevokedRefreshToken>();
// Person entities
public DbSet<Person> Persons => Set<Person>();
public DbSet<KnownFace> KnownFaces => Set<KnownFace>();
@@ -0,0 +1,33 @@
using Heimdall.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Heimdall.Infrastructure.Data.Configurations;
public class RevokedRefreshTokenConfiguration : IEntityTypeConfiguration<RevokedRefreshToken>
{
public void Configure(EntityTypeBuilder<RevokedRefreshToken> builder)
{
builder.ToTable("revoked_refresh_tokens");
builder.HasKey(r => r.Id);
builder.Property(r => r.TokenHash)
.HasMaxLength(128)
.IsRequired()
.IsUnicode(false);
builder.Property(r => r.UserId)
.IsRequired();
builder.Property(r => r.RevokedAt)
.HasDefaultValueSql("NOW()");
builder.Property(r => r.ExpiresAt)
.IsRequired();
// Indexes for lookup and cleanup
builder.HasIndex(r => r.TokenHash).IsUnique();
builder.HasIndex(r => r.ExpiresAt);
}
}
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 AddRevokedRefreshTokens : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "revoked_refresh_tokens",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
TokenHash = table.Column<string>(type: "character varying(128)", unicode: false, maxLength: 128, nullable: false),
UserId = table.Column<Guid>(type: "uuid", nullable: false),
RevokedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
ExpiresAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_revoked_refresh_tokens", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_revoked_refresh_tokens_ExpiresAt",
table: "revoked_refresh_tokens",
column: "ExpiresAt");
migrationBuilder.CreateIndex(
name: "IX_revoked_refresh_tokens_TokenHash",
table: "revoked_refresh_tokens",
column: "TokenHash",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "revoked_refresh_tokens");
}
}
}
@@ -1072,6 +1072,39 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("persons", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.RevokedRefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("RevokedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(128)
.IsUnicode(false)
.HasColumnType("character varying(128)");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("ExpiresAt");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("revoked_refresh_tokens", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.Site", b =>
{
b.Property<Guid>("Id")
@@ -1,6 +1,5 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Heimdall.Domain.Entities;
using Microsoft.Extensions.Configuration;
@@ -12,7 +11,7 @@ namespace Heimdall.Infrastructure.Security;
public interface IJwtService
{
(string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions);
string GenerateRefreshToken();
(string token, DateTime expiresAt) GenerateRefreshToken(AppUser user);
ClaimsPrincipal? ValidateRefreshToken(string refreshToken);
string? GetUserIdFromExpiredToken(string token);
}
@@ -63,12 +62,31 @@ public class JwtService : IJwtService
return (new JwtSecurityTokenHandler().WriteToken(token), expiresAt);
}
public string GenerateRefreshToken()
public (string token, DateTime expiresAt) GenerateRefreshToken(AppUser user)
{
var randomBytes = new byte[64];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(randomBytes);
return Convert.ToBase64String(randomBytes);
var refreshKeyValue = _configuration["Jwt:RefreshKey"]
?? throw new InvalidOperationException("Jwt:RefreshKey is not configured");
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(refreshKeyValue));
var expiresAt = DateTime.UtcNow.AddDays(
double.TryParse(_configuration["Jwt:RefreshTokenExpiryDays"], out var days) ? days : 7);
var tokenId = Guid.NewGuid().ToString(); // unique jti for DB revocation tracking
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new(JwtRegisteredClaimNames.Jti, tokenId),
new(JwtRegisteredClaimNames.Email, user.Email ?? ""),
};
var token = new JwtSecurityToken(
issuer: _configuration["Jwt:Issuer"] ?? "heimdall",
audience: _configuration["Jwt:Audience"] ?? "heimdall-api",
claims: claims,
expires: expiresAt,
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
return (new JwtSecurityTokenHandler().WriteToken(token), expiresAt);
}
public ClaimsPrincipal? ValidateRefreshToken(string refreshToken)
@@ -1,7 +1,5 @@
using System.Collections.Concurrent;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
@@ -16,12 +14,6 @@ namespace Heimdall.Infrastructure.Services;
public class AuthService : IAuthService
{
/// <summary>
/// In-memory refresh token blacklist. In multi-instance deployments,
/// replace with a DB-backed store (e.g. RevokedRefreshToken entity).
/// </summary>
private static readonly ConcurrentDictionary<string, byte> _revokedTokens = new(StringComparer.Ordinal);
private readonly UserManager<AppUser> _userManager;
private readonly SignInManager<AppUser> _signInManager;
private readonly IJwtService _jwtService;
@@ -195,13 +187,6 @@ public class AuthService : IAuthService
public async Task<ServiceResult<AuthResponse>> RefreshTokenAsync(string refreshToken, CancellationToken ct)
{
var tokenHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(refreshToken))).ToLowerInvariant();
if (_revokedTokens.ContainsKey(tokenHash))
{
_logger.LogWarning("RefreshToken: Token revoked hash={HashPrefix}", tokenHash[..8]);
return ServiceResult<AuthResponse>.Unauthorized("Refresh token has been revoked");
}
var principal = _jwtService.ValidateRefreshToken(refreshToken);
if (principal is null)
{
@@ -209,6 +194,19 @@ public class AuthService : IAuthService
return ServiceResult<AuthResponse>.Unauthorized("Invalid or expired refresh token");
}
var tokenId = principal.FindFirstValue(JwtRegisteredClaimNames.Jti);
if (tokenId is not null)
{
// Check DB-backed revocation list (survives restarts, works in multi-instance)
var revoked = await _db.Set<RevokedRefreshToken>()
.AnyAsync(r => r.TokenHash == tokenId, ct);
if (revoked)
{
_logger.LogWarning("RefreshToken: Token revoked jti={Jti}", tokenId[..Math.Min(8, tokenId.Length)]);
return ServiceResult<AuthResponse>.Unauthorized("Refresh token has been revoked");
}
}
var userId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
if (userId is null)
{
@@ -249,6 +247,28 @@ public class AuthService : IAuthService
return ServiceResult.Success();
}
public async Task<ServiceResult> Disable2faAsync(Guid userId, CancellationToken ct)
{
_logger.LogDebug("Disable2fa: UserId={UserId}", userId);
var user = await _userManager.FindByIdAsync(userId.ToString());
if (user is null)
{
_logger.LogWarning("Disable2fa: User not found UserId={UserId}", userId);
return ServiceResult.NotFound("User not found");
}
var result = await _userManager.SetTwoFactorEnabledAsync(user, false);
if (!result.Succeeded)
{
_logger.LogError("Disable2fa: Failed UserId={UserId}", userId);
return ServiceResult.Failure("Failed to disable 2FA");
}
_logger.LogInformation("Disable2fa: Disabled UserId={UserId}", userId);
return ServiceResult.Success();
}
public async Task<ServiceResult> ChangePasswordAsync(Guid userId, string currentPassword, string newPassword, CancellationToken ct)
{
_logger.LogDebug("ChangePassword: UserId={UserId}", userId);
@@ -310,8 +330,23 @@ public class AuthService : IAuthService
if (!string.IsNullOrEmpty(refreshToken))
{
var tokenHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(refreshToken))).ToLowerInvariant();
_revokedTokens.TryAdd(tokenHash, 0);
// Extract jti from the refresh token JWT and persist to DB
try
{
var handler = new JwtSecurityTokenHandler();
var jwtToken = handler.ReadJwtToken(refreshToken);
var tokenId = jwtToken.Id;
if (!string.IsNullOrEmpty(tokenId))
{
_db.Set<RevokedRefreshToken>().Add(new RevokedRefreshToken(
tokenId, userId, jwtToken.ValidTo));
}
}
catch (Exception ex)
{
_logger.LogWarning("Logout: Failed to parse refresh token: {Message}", ex.Message);
}
_db.AuditLogs.Add(new AuditLog(userId, "User.Logout", "User", userId.ToString()));
await _db.SaveChangesWithRetryAsync(ct: ct);
@@ -327,7 +362,7 @@ public class AuthService : IAuthService
AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : []).ToList();
var (accessToken, expiresAt) = _jwtService.GenerateAccessToken(user, roles, permissions);
var refreshToken = _jwtService.GenerateRefreshToken();
var (refreshToken, _) = _jwtService.GenerateRefreshToken(user);
return ServiceResult<AuthResponse>.Success(new AuthResponse(
accessToken,
@@ -312,13 +312,15 @@ public class UserService : IUserService
const string digits = "0123456789";
const string special = "!@#$%";
// Guarantee at least 1 digit and 1 lowercase (Identity requirements)
// Remaining chars are random from the full set
// Guarantee at least 1 char from each required category
// (uppercase, lowercase, digit, non-alphanumeric) per current Identity policy.
var chars = (lower + upper + digits + special).ToCharArray();
var password = new char[16];
password[0] = digits[RandomNumberGenerator.GetInt32(digits.Length)];
password[1] = lower[RandomNumberGenerator.GetInt32(lower.Length)];
for (int i = 2; i < password.Length; i++)
password[2] = upper[RandomNumberGenerator.GetInt32(upper.Length)];
password[3] = special[RandomNumberGenerator.GetInt32(special.Length)];
for (int i = 4; i < password.Length; i++)
password[i] = chars[RandomNumberGenerator.GetInt32(chars.Length)];
// Shuffle to avoid predictable position pattern
+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;
}
}
@@ -18,6 +18,7 @@ public class HeimdallWebApplicationFactory : WebApplicationFactory<Program>
builder.UseSetting("InMemoryDbName", _dbName);
// JWT config
builder.UseSetting("Jwt:Key", "ThisIsATestKeyThatIsAtLeast32BytesLong!");
builder.UseSetting("Jwt:RefreshKey", "ThisIsATestRefreshKeyThatIsAlso32Bytes!");
builder.UseSetting("Jwt:Issuer", "heimdall-test");
builder.UseSetting("Jwt:Audience", "heimdall-test");
}