Browse Source

Merge remote-tracking branch 'origin/rel-10.7' into auto-merge-forward/rel-10.7-to-dev-110

pull/26355/head
github-actions[bot] 4 weeks ago
parent
commit
cfa99766d9
  1. 1
      docs/en/modules/identity/session-management.md
  2. 6
      framework/src/Volo.Abp.AspNetCore.Authentication.JwtBearer/Volo/Abp/AspNetCore/Authentication/JwtBearer/DynamicClaims/WebRemoteDynamicClaimsPrincipalContributorCache.cs
  3. 6
      framework/src/Volo.Abp.AspNetCore.Mvc.Client.Common/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributorCache.cs
  4. 9
      framework/src/Volo.Abp.AspNetCore.Mvc.Client/Volo/Abp/AspNetCore/Mvc/Client/AbpRemoteDynamicClaimsCookieAuthenticationOptionsExtensions.cs
  5. 5
      framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/AbpDynamicClaimCacheItem.cs
  6. 9
      framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/RemoteDynamicClaimsPrincipalContributorBase.cs
  7. 9
      framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/RemoteDynamicClaimsPrincipalContributorCacheBase.cs
  8. 35
      framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/AbpRemoteDynamicClaimsCookieAuthenticationOptionsExtensions_Tests.cs
  9. 81
      framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributorCacheFailure_Tests.cs
  10. 85
      framework/test/Volo.Abp.AspNetCore.Mvc.Client.Tests/Volo/Abp/AspNetCore/Mvc/Client/RemoteDynamicClaimsPrincipalContributor_Tests.cs

1
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.

6
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<bool> 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

6
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<bool> 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<AbpDynamicClaimCacheItem> GetAsync(Guid userId, Guid? tenantId, string accessToken)
{
return GetAsync(userId, tenantId, () => RefreshAsync(userId, tenantId, accessToken));

9
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<ICurrentTenant>().Change(tenantId))
{
var sessionId = identity!.FindSessionId();
if (!sessionId.IsNullOrWhiteSpace() && await dynamicClaimsCache.IsSessionRevokedAsync(sessionId!))
{
httpContext.RequestServices
.GetRequiredService<ILogger<AbpAspNetCoreMvcClientModule>>()
.LogWarning($"The session: {sessionId} of user: {userId.Value} is revoked, the authentication cookie is rejected.");
return false;
}
await dynamicClaimsCache.GetAsync(userId.Value, tenantId, accessToken);
}

5
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}";
}
}

9
framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/RemoteDynamicClaimsPrincipalContributorBase.cs

@ -30,6 +30,15 @@ public abstract class RemoteDynamicClaimsPrincipalContributorBase<TContributor,
AbpDynamicClaimCacheItem dynamicClaims;
try
{
var sessionId = identity.FindSessionId();
if (!sessionId.IsNullOrWhiteSpace() && await dynamicClaimsCache.IsSessionRevokedAsync(sessionId!))
{
context.ClaimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity());
context.GetRequiredService<ILogger<TContributor>>()
.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)

9
framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/RemoteDynamicClaimsPrincipalContributorCacheBase.cs

@ -54,6 +54,15 @@ public abstract class RemoteDynamicClaimsPrincipalContributorCacheBase<TContribu
return dynamicClaims;
}
/// <summary>
/// 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.
/// </summary>
public virtual Task<bool> IsSessionRevokedAsync(string sessionId)
{
return Task.FromResult(false);
}
protected abstract Task<AbpDynamicClaimCacheItem?> GetCacheAsync(Guid userId, Guid? tenantId = null);
protected abstract Task RefreshAsync(Guid userId, Guid? tenantId = null);

35
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<IDistributedCache<AbpDynamicClaimCacheItem>>();
// 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<IDistributedCache<AbpDynamicClaimCacheItem>>();
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<CookieValidatePrincipalContext> ValidatePrincipalAsync(Guid userId, string accessToken = "test-access-token")
private async Task<CookieValidatePrincipalContext> 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)

81
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<IDistributedCache, RevokedSessionFailingCache>());
services.Configure<AbpClaimsPrincipalFactoryOptions>(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<IDistributedCache<AbpDynamicClaimCacheItem>>().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<RemoteDynamicClaimsPrincipalContributor>().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<byte[]> 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.");
}
}
}
}

85
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<AbpClaimsPrincipalFactoryOptions>(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<Guid> CacheUserAsync()
{
var userId = Guid.NewGuid();
await GetRequiredService<IDistributedCache<AbpDynamicClaimCacheItem>>().SetAsync(
AbpDynamicClaimCacheItem.CalculateCacheKey(userId, null),
new AbpDynamicClaimCacheItem(new() { new AbpDynamicClaim(AbpClaimTypes.UserName, "john") }));
return userId;
}
private Task RevokeSessionAsync(string sessionId)
{
return GetRequiredService<IDistributedCache<AbpDynamicClaimCacheItem>>().SetAsync(
AbpDynamicClaimCacheItem.CalculateRevokedSessionCacheKey(sessionId),
new AbpDynamicClaimCacheItem());
}
private async Task<ClaimsPrincipal> 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<RemoteDynamicClaimsPrincipalContributor>().ContributeAsync(context);
return context.ClaimsPrincipal;
}
}
Loading…
Cancel
Save