From ef62a3714f50cba9d3b9cd70163a3e9796da56a4 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 08:11:32 +0100 Subject: [PATCH] Identity: gelijktijdige refresh met hetzelfde token (20 s coulance) trekt de sessies niet meer in; geen foutlog voor afgebroken verzoeken Co-Authored-By: Claude Sonnet 5.5 --- .../Identity/AuthServiceTests.cs | 31 +++++++++++++++++++ .../Exceptions/GlobalExceptionHandler.cs | 17 +++++++++- .../Identity/Services/AuthService.cs | 18 +++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/src/SlpModularCms.Core.Tests/Identity/AuthServiceTests.cs b/src/SlpModularCms.Core.Tests/Identity/AuthServiceTests.cs index b1e658d..c1e7d47 100644 --- a/src/SlpModularCms.Core.Tests/Identity/AuthServiceTests.cs +++ b/src/SlpModularCms.Core.Tests/Identity/AuthServiceTests.cs @@ -172,6 +172,37 @@ public class AuthServiceTests allTokens.Should().AllSatisfy(t => t.IsRevoked.Should().BeTrue()); } + [Fact] + public async Task RefreshTokenAsync_ShouldAnswerAConcurrentSecondRefresh_WithoutRevokingTheSessions() + { + var user = new ApplicationUser { Id = Guid.NewGuid(), Email = "user@example.com", IsActive = true }; + _context.Users.Add(user); + _context.RefreshTokens.Add(new RefreshToken { Token = "old", UserId = user.Id, ExpiryDate = DateTimeOffset.UtcNow.AddDays(1), IsUsed = true, CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-10) }); + _context.RefreshTokens.Add(new RefreshToken { Token = "new", UserId = user.Id, ExpiryDate = DateTimeOffset.UtcNow.AddDays(1), CreatedAt = DateTimeOffset.UtcNow.AddSeconds(-2) }); + await _context.SaveChangesAsync(); + _userManager.GetRolesAsync(Arg.Any()).Returns(new List { "User" }); + + var result = await _service.RefreshTokenAsync("old"); + + result.AccessToken.Should().NotBeNullOrEmpty(); + (await _context.RefreshTokens.Where(t => t.UserId == user.Id && t.Token != "old").ToListAsync()).Should().OnlyContain(t => !t.IsRevoked); + } + + [Fact] + public async Task RefreshTokenAsync_ShouldStillRevokeEverything_WhenAUsedTokenComesBackAfterTheGracePeriod() + { + var user = new ApplicationUser { Id = Guid.NewGuid(), Email = "user@example.com", IsActive = true }; + _context.Users.Add(user); + _context.RefreshTokens.Add(new RefreshToken { Token = "old", UserId = user.Id, ExpiryDate = DateTimeOffset.UtcNow.AddDays(1), IsUsed = true, CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-10) }); + _context.RefreshTokens.Add(new RefreshToken { Token = "new", UserId = user.Id, ExpiryDate = DateTimeOffset.UtcNow.AddDays(1), CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-5) }); + await _context.SaveChangesAsync(); + + var act = () => _service.RefreshTokenAsync("old"); + + await act.Should().ThrowAsync(); + (await _context.RefreshTokens.ToListAsync()).Should().AllSatisfy(t => t.IsRevoked.Should().BeTrue()); + } + [Fact] public async Task RefreshTokenAsync_ShouldReturnNewTokens_WhenTokenValid() { diff --git a/src/SlpModularCms.Core/Exceptions/GlobalExceptionHandler.cs b/src/SlpModularCms.Core/Exceptions/GlobalExceptionHandler.cs index c68bf20..6ab83d8 100644 --- a/src/SlpModularCms.Core/Exceptions/GlobalExceptionHandler.cs +++ b/src/SlpModularCms.Core/Exceptions/GlobalExceptionHandler.cs @@ -27,6 +27,14 @@ public class GlobalExceptionHandler : IExceptionHandler Exception exception, CancellationToken cancellationToken) { + // The client went away (closed tab, navigation, a poll that was replaced): nobody is waiting for an answer, so + // this is neither an error nor worth a warning, and writing a response to a closed connection would only fail again. + if (httpContext.RequestAborted.IsCancellationRequested && exception is OperationCanceledException) + { + _logger.LogDebug("Request cancelled by the client: {Path}", httpContext.Request.Path); + return true; + } + var traceId = Activity.Current?.Id ?? httpContext.TraceIdentifier; var (statusCode, title) = MapException(exception); @@ -67,7 +75,14 @@ public class GlobalExceptionHandler : IExceptionHandler httpContext.Response.StatusCode = statusCode; - await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken); + try + { + await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken); + } + catch (OperationCanceledException) when (httpContext.RequestAborted.IsCancellationRequested) + { + // The client left while the answer was being written; there is nobody to tell. + } return true; } diff --git a/src/SlpModularCms.Core/Identity/Services/AuthService.cs b/src/SlpModularCms.Core/Identity/Services/AuthService.cs index 75afeb5..f4d21c6 100644 --- a/src/SlpModularCms.Core/Identity/Services/AuthService.cs +++ b/src/SlpModularCms.Core/Identity/Services/AuthService.cs @@ -55,6 +55,9 @@ public class AuthService : IAuthService return await GenerateTokenResponseAsync(user); } + /// How long after a refresh token was replaced the same token is still answered with a fresh pair (concurrent refreshes). + private static readonly TimeSpan ConcurrentRefreshGrace = TimeSpan.FromSeconds(20); + public async Task RefreshTokenAsync(string refreshToken) { var savedRefreshToken = await _context.RefreshTokens @@ -68,6 +71,21 @@ public class AuthService : IAuthService if (savedRefreshToken.IsUsed) { + // Two requests (two tabs, or a page that wakes up after a restart) can send the same refresh token at the + // same moment; the second one arrives after the first rotated it. That is not theft: when this token was + // replaced a moment ago (a newer token of the same user was created within the grace period), give this + // caller a fresh pair as well and leave the sessions alone. A real replay later still revokes everything. + var graceStart = DateTimeOffset.UtcNow - ConcurrentRefreshGrace; + var replacedJustNow = await _context.RefreshTokens.AnyAsync(t => + t.UserId == savedRefreshToken.UserId + && !t.IsRevoked + && t.CreatedAt > savedRefreshToken.CreatedAt + && t.CreatedAt >= graceStart); + if (replacedJustNow && savedRefreshToken.User.IsActive) + { + return await GenerateTokenResponseAsync(savedRefreshToken.User); + } + // Re-use detection: trek alle tokens van de gebruiker in var userId = savedRefreshToken.UserId; var allTokens = await _context.RefreshTokens.Where(t => t.UserId == userId).ToListAsync();