From 7b68260631cd4f2964408c651ef96f8291fe065a Mon Sep 17 00:00:00 2001 From: maliming Date: Thu, 29 Oct 2026 14:15:21 +0800 Subject: [PATCH] Reject revoked sessions in the remote dynamic claims --- .../en/modules/identity/session-management.md | 1 + ...eDynamicClaimsPrincipalContributorCache.cs | 6 ++ ...eDynamicClaimsPrincipalContributorCache.cs | 6 ++ ...msCookieAuthenticationOptionsExtensions.cs | 9 ++ .../Claims/AbpDynamicClaimCacheItem.cs | 5 ++ ...teDynamicClaimsPrincipalContributorBase.cs | 9 ++ ...amicClaimsPrincipalContributorCacheBase.cs | 9 ++ ...ieAuthenticationOptionsExtensions_Tests.cs | 35 +++++++- ...sPrincipalContributorCacheFailure_Tests.cs | 81 ++++++++++++++++++ ...DynamicClaimsPrincipalContributor_Tests.cs | 85 +++++++++++++++++++ 10 files changed, 245 insertions(+), 1 deletion(-) create mode 100644 framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributorCacheFailure_Tests.cs create mode 100644 framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributor_Tests.cs diff --git a/docs/en/modules/identity/session-management.md b/docs/en/modules/identity/session-management.md index 08ae3a5fda..78173360ba 100644 --- a/docs/en/modules/identity/session-management.md +++ b/docs/en/modules/identity/session-management.md @@ -58,6 +58,7 @@ This feature depends on the [Dynamic Claims](../../framework/fundamentals/dynami * The `IdentitySessionChecker` will check the `sessionid` that exists and update the `LastAccessed` and `IpAddress` to the cache. * The `IdentitySessionManager` is used to get one or a list of sessions and update the` LastAccessed` and `IpAddress` from the cache to the database. * The module will remove the session when logging out. +* When a session is removed, the module also remembers it as revoked in the distributed cache (if dynamic claims are enabled). The applications that use the remote dynamic claims (`WebRemoteDynamicClaimsPrincipalContributor` or `RemoteDynamicClaimsPrincipalContributor`) reject the tokens of a revoked session, even when the dynamic claims of the user are cached for another session. The `RevokedSessionCacheExpiration` property of `IdentitySessionCheckerOptions` sets how long it is remembered and defaults to 2 hours. Keep it longer than your access token lifetime plus the clock skew. * The `IdentitySessionCleanupBackgroundWorker` will remove the inactive sessions. * Once a new session has been created, we will remove the other sessions based on the `PreventConcurrentLogin` setting. * The `IdentitySessionManager` is used to manage/maintain the sessions. Please use this class instead of directly using the repository. diff --git a/framework/src/Volo.Abp.AspNetCore.Authentication.JwtBearer/Volo/Abp/AspNetCore/Authentication/JwtBearer/DynamicClaims/WebRemoteDynamicClaimsPrincipalContributorCache.cs b/framework/src/Volo.Abp.AspNetCore.Authentication.JwtBearer/Volo/Abp/AspNetCore/Authentication/JwtBearer/DynamicClaims/WebRemoteDynamicClaimsPrincipalContributorCache.cs index 63c2d6d082..259a13c8e2 100644 --- a/framework/src/Volo.Abp.AspNetCore.Authentication.JwtBearer/Volo/Abp/AspNetCore/Authentication/JwtBearer/DynamicClaims/WebRemoteDynamicClaimsPrincipalContributorCache.cs +++ b/framework/src/Volo.Abp.AspNetCore.Authentication.JwtBearer/Volo/Abp/AspNetCore/Authentication/JwtBearer/DynamicClaims/WebRemoteDynamicClaimsPrincipalContributorCache.cs @@ -39,6 +39,12 @@ public class WebRemoteDynamicClaimsPrincipalContributorCache : RemoteDynamicClai return await Cache.GetAsync(AbpDynamicClaimCacheItem.CalculateCacheKey(userId, tenantId)); } + public async override Task IsSessionRevokedAsync(string sessionId) + { + // A failed read must not count as a valid session, so the error isn't hidden. + return await Cache.GetAsync(AbpDynamicClaimCacheItem.CalculateRevokedSessionCacheKey(sessionId), hideErrors: false) != null; + } + protected async override Task RefreshAsync(Guid userId, Guid? tenantId = null) { try diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc.Client.Common/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributorCache.cs b/framework/src/Volo.Abp.AspNetCore.Mvc.Client.Common/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributorCache.cs index 8f81b5aab4..dd6455272d 100644 --- a/framework/src/Volo.Abp.AspNetCore.Mvc.Client.Common/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributorCache.cs +++ b/framework/src/Volo.Abp.AspNetCore.Mvc.Client.Common/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributorCache.cs @@ -47,6 +47,12 @@ public class RemoteDynamicClaimsPrincipalContributorCache : RemoteDynamicClaimsP return await Cache.GetAsync(AbpDynamicClaimCacheItem.CalculateCacheKey(userId, tenantId)); } + public async override Task IsSessionRevokedAsync(string sessionId) + { + // A failed read must not count as a valid session, so the error isn't hidden. + return await Cache.GetAsync(AbpDynamicClaimCacheItem.CalculateRevokedSessionCacheKey(sessionId), hideErrors: false) != null; + } + public virtual Task GetAsync(Guid userId, Guid? tenantId, string accessToken) { return GetAsync(userId, tenantId, () => RefreshAsync(userId, tenantId, accessToken)); diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc.Client/Volo/Abp/AspNetCore/Mvc/Client/AbpRemoteDynamicClaimsCookieAuthenticationOptionsExtensions.cs b/framework/src/Volo.Abp.AspNetCore.Mvc.Client/Volo/Abp/AspNetCore/Mvc/Client/AbpRemoteDynamicClaimsCookieAuthenticationOptionsExtensions.cs index 4887429898..edcf69c34b 100644 --- a/framework/src/Volo.Abp.AspNetCore.Mvc.Client/Volo/Abp/AspNetCore/Mvc/Client/AbpRemoteDynamicClaimsCookieAuthenticationOptionsExtensions.cs +++ b/framework/src/Volo.Abp.AspNetCore.Mvc.Client/Volo/Abp/AspNetCore/Mvc/Client/AbpRemoteDynamicClaimsCookieAuthenticationOptionsExtensions.cs @@ -88,6 +88,15 @@ public static class AbpRemoteDynamicClaimsCookieAuthenticationOptionsExtensions var tenantId = identity!.FindTenantId(); using (httpContext.RequestServices.GetRequiredService().Change(tenantId)) { + var sessionId = identity!.FindSessionId(); + if (!sessionId.IsNullOrWhiteSpace() && await dynamicClaimsCache.IsSessionRevokedAsync(sessionId!)) + { + httpContext.RequestServices + .GetRequiredService>() + .LogWarning($"The session: {sessionId} of user: {userId.Value} is revoked, the authentication cookie is rejected."); + return false; + } + await dynamicClaimsCache.GetAsync(userId.Value, tenantId, accessToken); } diff --git a/framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/AbpDynamicClaimCacheItem.cs b/framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/AbpDynamicClaimCacheItem.cs index 8c25cb19e7..71c9634d7b 100644 --- a/framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/AbpDynamicClaimCacheItem.cs +++ b/framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/AbpDynamicClaimCacheItem.cs @@ -22,4 +22,9 @@ public class AbpDynamicClaimCacheItem { return $"{tenantId}-{userId}"; } + + public static string CalculateRevokedSessionCacheKey(string sessionId) + { + return $"revoked-session:{sessionId}"; + } } diff --git a/framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/RemoteDynamicClaimsPrincipalContributorBase.cs b/framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/RemoteDynamicClaimsPrincipalContributorBase.cs index b54f5becbd..72164c3d58 100644 --- a/framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/RemoteDynamicClaimsPrincipalContributorBase.cs +++ b/framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/RemoteDynamicClaimsPrincipalContributorBase.cs @@ -30,6 +30,15 @@ public abstract class RemoteDynamicClaimsPrincipalContributorBase>() + .LogWarning($"The session: {sessionId} of user: {userId.Value} is revoked, the claims principal is cleared."); + return; + } + dynamicClaims = await dynamicClaimsCache.GetAsync(userId.Value, identity.FindTenantId()); } catch (Exception e) diff --git a/framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/RemoteDynamicClaimsPrincipalContributorCacheBase.cs b/framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/RemoteDynamicClaimsPrincipalContributorCacheBase.cs index e8cedc77e9..23b2fbd56b 100644 --- a/framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/RemoteDynamicClaimsPrincipalContributorCacheBase.cs +++ b/framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/RemoteDynamicClaimsPrincipalContributorCacheBase.cs @@ -54,6 +54,15 @@ public abstract class RemoteDynamicClaimsPrincipalContributorCacheBase + /// Whether the session was revoked (for example by a logout). The dynamic claims are cached per user, + /// so a cached user doesn't mean the session of the current token is still valid. + /// + public virtual Task IsSessionRevokedAsync(string sessionId) + { + return Task.FromResult(false); + } + protected abstract Task GetCacheAsync(Guid userId, Guid? tenantId = null); protected abstract Task RefreshAsync(Guid userId, Guid? tenantId = null); diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/AbpRemoteDynamicClaimsCookieAuthenticationOptionsExtensions_Tests.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/AbpRemoteDynamicClaimsCookieAuthenticationOptionsExtensions_Tests.cs index 594d250330..ce38eb3a02 100644 --- a/framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/AbpRemoteDynamicClaimsCookieAuthenticationOptionsExtensions_Tests.cs +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/AbpRemoteDynamicClaimsCookieAuthenticationOptionsExtensions_Tests.cs @@ -63,6 +63,35 @@ public class AbpRemoteDynamicClaimsCookieAuthenticationOptionsExtensions_Tests : _remoteRefreshResponseHandler.ReceivedAccessTokens.ShouldBeEmpty(); } + [Fact] + public async Task Should_Reject_The_Principal_When_The_Session_Is_Revoked() + { + var userId = Guid.NewGuid(); + var cache = GetRequiredService>(); + // Another session of the user filled the cache. + await cache.SetAsync(AbpDynamicClaimCacheItem.CalculateCacheKey(userId, null), new AbpDynamicClaimCacheItem()); + await cache.SetAsync(AbpDynamicClaimCacheItem.CalculateRevokedSessionCacheKey("session-a"), new AbpDynamicClaimCacheItem()); + + var context = await ValidatePrincipalAsync(userId, sessionId: "session-a"); + + context.Principal.ShouldBeNull(); + _remoteRefreshResponseHandler.ReceivedAccessTokens.ShouldBeEmpty(); + } + + [Fact] + public async Task Should_Keep_The_Principal_Of_Another_Session_When_A_Session_Is_Revoked() + { + var userId = Guid.NewGuid(); + var cache = GetRequiredService>(); + await cache.SetAsync(AbpDynamicClaimCacheItem.CalculateCacheKey(userId, null), new AbpDynamicClaimCacheItem()); + await cache.SetAsync(AbpDynamicClaimCacheItem.CalculateRevokedSessionCacheKey("session-a"), new AbpDynamicClaimCacheItem()); + + var context = await ValidatePrincipalAsync(userId, sessionId: "session-b"); + + context.Principal.ShouldNotBeNull(); + _remoteRefreshResponseHandler.ReceivedAccessTokens.ShouldBeEmpty(); + } + [Fact] public async Task Should_Keep_The_Principal_When_There_Is_No_Access_Token() { @@ -72,13 +101,17 @@ public class AbpRemoteDynamicClaimsCookieAuthenticationOptionsExtensions_Tests : _remoteRefreshResponseHandler.ReceivedAccessTokens.ShouldBeEmpty(); } - private async Task ValidatePrincipalAsync(Guid userId, string accessToken = "test-access-token") + private async Task ValidatePrincipalAsync(Guid userId, string accessToken = "test-access-token", string sessionId = null) { var options = new CookieAuthenticationOptions().ValidateRemoteDynamicClaims(); var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, AbpClaimTypes.UserName, AbpClaimTypes.Role); identity.AddClaim(new Claim(AbpClaimTypes.UserId, userId.ToString())); identity.AddClaim(new Claim(AbpClaimTypes.UserName, "john")); + if (sessionId != null) + { + identity.AddClaim(new Claim(AbpClaimTypes.SessionId, sessionId)); + } var properties = new AuthenticationProperties(); if (accessToken != null) diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributorCacheFailure_Tests.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributorCacheFailure_Tests.cs new file mode 100644 index 0000000000..a3b1dbca01 --- /dev/null +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributorCacheFailure_Tests.cs @@ -0,0 +1,81 @@ +using System; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Shouldly; +using Volo.Abp.Caching; +using Volo.Abp.Security.Claims; +using Xunit; + +namespace Volo.Abp.AspNetCore.Mvc.Client; + +public class RemoteDynamicClaimsPrincipalContributorCacheFailure_Tests : AbpAspNetCoreMvcClientTestBase +{ + protected override void AfterAddApplication(IServiceCollection services) + { + services.Replace(ServiceDescriptor.Singleton()); + services.Configure(options => + { + options.IsDynamicClaimsEnabled = true; + }); + } + + [Fact] + public async Task Should_Clear_The_Principal_When_The_Revoked_Sessions_Can_Not_Be_Read() + { + var userId = Guid.NewGuid(); + await GetRequiredService>().SetAsync( + AbpDynamicClaimCacheItem.CalculateCacheKey(userId, null), + new AbpDynamicClaimCacheItem()); + + var identity = new ClaimsIdentity("Bearer", AbpClaimTypes.UserName, AbpClaimTypes.Role); + identity.AddClaim(new Claim(AbpClaimTypes.UserId, userId.ToString())); + identity.AddClaim(new Claim(AbpClaimTypes.SessionId, "session-a")); + var context = new AbpClaimsPrincipalContributorContext(new ClaimsPrincipal(identity), ServiceProvider); + + await GetRequiredService().ContributeAsync(context); + + context.ClaimsPrincipal.Identity!.IsAuthenticated.ShouldBeFalse(); + } + + private class RevokedSessionFailingCache : IDistributedCache + { + private readonly MemoryDistributedCache _cache = new(Microsoft.Extensions.Options.Options.Create(new MemoryDistributedCacheOptions())); + + public byte[] Get(string key) + { + ThrowForRevokedSession(key); + return _cache.Get(key); + } + + public Task GetAsync(string key, CancellationToken token = default) + { + ThrowForRevokedSession(key); + return _cache.GetAsync(key, token); + } + + public void Set(string key, byte[] value, DistributedCacheEntryOptions options) => _cache.Set(key, value, options); + + public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default) => _cache.SetAsync(key, value, options, token); + + public void Refresh(string key) => _cache.Refresh(key); + + public Task RefreshAsync(string key, CancellationToken token = default) => _cache.RefreshAsync(key, token); + + public void Remove(string key) => _cache.Remove(key); + + public Task RemoveAsync(string key, CancellationToken token = default) => _cache.RemoveAsync(key, token); + + private static void ThrowForRevokedSession(string key) + { + if (key.Contains("revoked-session:")) + { + throw new InvalidOperationException("The cache is not available."); + } + } + } +} diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributor_Tests.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributor_Tests.cs new file mode 100644 index 0000000000..2831e5aa8a --- /dev/null +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributor_Tests.cs @@ -0,0 +1,85 @@ +using System; +using System.Security.Claims; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Volo.Abp.Caching; +using Volo.Abp.Security.Claims; +using Xunit; + +namespace Volo.Abp.AspNetCore.Mvc.Client; + +public class RemoteDynamicClaimsPrincipalContributor_Tests : AbpAspNetCoreMvcClientTestBase +{ + protected override void AfterAddApplication(IServiceCollection services) + { + services.Configure(options => + { + options.IsDynamicClaimsEnabled = true; + }); + } + + [Fact] + public async Task Should_Clear_The_Principal_When_The_Session_Is_Revoked() + { + var userId = await CacheUserAsync(); + await RevokeSessionAsync("session-a"); + + var principal = await ContributeAsync(userId, "session-a"); + + principal.Identity!.IsAuthenticated.ShouldBeFalse(); + } + + [Fact] + public async Task Should_Keep_The_Principal_Of_Another_Session() + { + var userId = await CacheUserAsync(); + await RevokeSessionAsync("session-a"); + + var principal = await ContributeAsync(userId, "session-b"); + + principal.Identity!.IsAuthenticated.ShouldBeTrue(); + principal.FindFirst(AbpClaimTypes.UserName)!.Value.ShouldBe("john"); + } + + [Fact] + public async Task Should_Keep_The_Principal_Without_A_Session_Id() + { + var userId = await CacheUserAsync(); + + var principal = await ContributeAsync(userId, sessionId: null); + + principal.Identity!.IsAuthenticated.ShouldBeTrue(); + } + + private async Task CacheUserAsync() + { + var userId = Guid.NewGuid(); + await GetRequiredService>().SetAsync( + AbpDynamicClaimCacheItem.CalculateCacheKey(userId, null), + new AbpDynamicClaimCacheItem(new() { new AbpDynamicClaim(AbpClaimTypes.UserName, "john") })); + return userId; + } + + private Task RevokeSessionAsync(string sessionId) + { + return GetRequiredService>().SetAsync( + AbpDynamicClaimCacheItem.CalculateRevokedSessionCacheKey(sessionId), + new AbpDynamicClaimCacheItem()); + } + + private async Task ContributeAsync(Guid userId, string sessionId) + { + var identity = new ClaimsIdentity("Bearer", AbpClaimTypes.UserName, AbpClaimTypes.Role); + identity.AddClaim(new Claim(AbpClaimTypes.UserId, userId.ToString())); + identity.AddClaim(new Claim(AbpClaimTypes.UserName, "john")); + if (sessionId != null) + { + identity.AddClaim(new Claim(AbpClaimTypes.SessionId, sessionId)); + } + + var context = new AbpClaimsPrincipalContributorContext(new ClaimsPrincipal(identity), ServiceProvider); + await GetRequiredService().ContributeAsync(context); + return context.ClaimsPrincipal; + } +}