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
@@ -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
|
||||
|
||||
Reference in new issue
Block a user