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 <noreply@anthropic.com>
This commit is contained in:
@@ -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<ApplicationUser>()).Returns(new List<string> { "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<UnauthorizedException>();
|
||||
(await _context.RefreshTokens.ToListAsync()).Should().AllSatisfy(t => t.IsRevoked.Should().BeTrue());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RefreshTokenAsync_ShouldReturnNewTokens_WhenTokenValid()
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -55,6 +55,9 @@ public class AuthService : IAuthService
|
||||
return await GenerateTokenResponseAsync(user);
|
||||
}
|
||||
|
||||
/// <summary>How long after a refresh token was replaced the same token is still answered with a fresh pair (concurrent refreshes).</summary>
|
||||
private static readonly TimeSpan ConcurrentRefreshGrace = TimeSpan.FromSeconds(20);
|
||||
|
||||
public async Task<TokenResponse> 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();
|
||||
|
||||
Reference in New Issue
Block a user