Skip to content

Commit

Permalink
feat(identity): calculate session expiration time from identity claim…
Browse files Browse the repository at this point in the history
… principal
  • Loading branch information
colinin committed Oct 24, 2024
1 parent 5d0d676 commit 36bc767
Show file tree
Hide file tree
Showing 6 changed files with 108 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,19 @@ await IdentitySessionStore.CreateAsync(

await IdentityDynamicClaimsPrincipalContributorCache.ClearAsync(userId.Value, tenantId);

await IdentitySessionCache.RefreshAsync(sessionId,
// 2024-10-10 从令牌中取颁布时间与过期时间计算时间戳,作为默认缓存过期时间
double? expiraIn = null;
var expirainTime = claimsPrincipal.FindExpirainTime();
var issuedTime = claimsPrincipal.FindIssuedTime();
if (expirainTime.HasValue && issuedTime.HasValue)
{
expiraIn = DateTimeOffset.FromUnixTimeMilliseconds(expirainTime.Value)
.Subtract(DateTimeOffset.FromUnixTimeMilliseconds(issuedTime.Value))
.TotalMicroseconds;
}

await IdentitySessionCache.RefreshAsync(
sessionId,
new IdentitySessionCacheItem(
device,
deviceDesc,
Expand All @@ -86,7 +98,9 @@ await IdentitySessionCache.RefreshAsync(sessionId,
clientIpAddress,
Clock.Now,
Clock.Now,
deviceInfo.IpRegion));
deviceInfo.IpRegion,
expiraIn),
cancellationToken);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using JetBrains.Annotations;
using System.Linq;
using System.Security.Claims;
using Volo.Abp;

namespace System.Security.Principal;
public static class AbpClaimsIdentityExpiraInExtensions
{
public static long? FindExpirainTime([NotNull] this ClaimsPrincipal principal)
{
return principal.FindLongClaimValue("exp");
}

public static long? FindIssuedTime([NotNull] this ClaimsPrincipal principal)
{
return principal.FindLongClaimValue("iat");
}

public static long? FindLongClaimValue([NotNull] this ClaimsPrincipal principal, string claimType)
{
Check.NotNull(principal, nameof(principal));

var longValueOrNull = principal.Claims?.FirstOrDefault(c => c.Type == claimType);
if (longValueOrNull == null || longValueOrNull.Value.IsNullOrWhiteSpace())
{
return null;
}

if (long.TryParse(longValueOrNull.Value, out var longValue))
{
return longValue;
}

return null;
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using LINGYUN.Abp.IP2Region;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Volo.Abp.AspNetCore;
using Volo.Abp.Modularity;

Expand All @@ -9,4 +11,8 @@ namespace LINGYUN.Abp.Identity.Session.AspNetCore;
[DependsOn(typeof(AbpIdentitySessionModule))]
public class AbpIdentitySessionAspNetCoreModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.Replace(ServiceDescriptor.Singleton<IIpLocationInfoProvider, IP2RegionLocationInfoProvider>());
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using IP2Region.Net.Abstractions;
using System;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;

namespace LINGYUN.Abp.Identity.Session.AspNetCore;
public class IP2RegionLocationInfoProvider : IIpLocationInfoProvider, ISingletonDependency

public class IP2RegionLocationInfoProvider : IIpLocationInfoProvider
{
protected static readonly LocationInfo _nullCache = null;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Caching;
Expand All @@ -9,6 +11,7 @@ namespace LINGYUN.Abp.Identity.Session;
public class DefaultIdentitySessionCache : IIdentitySessionCache, ITransientDependency
{
public ILogger<DefaultIdentitySessionCache> Logger { protected get; set; }

protected IDistributedCache<IdentitySessionCacheItem> Cache { get; }

public DefaultIdentitySessionCache(IDistributedCache<IdentitySessionCacheItem> cache)
Expand All @@ -31,8 +34,16 @@ public async virtual Task RefreshAsync(string sessionId, IdentitySessionCacheIte
Logger.LogDebug($"Refresh user session cache for: {sessionId}");

var cacheKey = IdentitySessionCacheItem.CalculateCacheKey(sessionId);

await Cache.SetAsync(cacheKey, cacheItem, token: cancellationToken);
DistributedCacheEntryOptions cacheOptions = null;
if (cacheItem.ExpiraIn.HasValue)
{
cacheOptions = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(cacheItem.ExpiraIn.Value),
};
}

await Cache.SetAsync(cacheKey, cacheItem, options: cacheOptions, token: cancellationToken);
}

public async virtual Task RemoveAsync(string sessionId, CancellationToken cancellationToken = default)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,46 @@ namespace LINGYUN.Abp.Identity.Session;
public class IdentitySessionCacheItem
{
private const string CacheKeyFormat = "s:{0}";

/// <summary>
/// 登录设备
/// </summary>
public string Device { get; set; }

/// <summary>
/// 设备描述
/// </summary>
public string DeviceInfo { get; set; }

/// <summary>
/// 用户Id
/// </summary>
public Guid UserId { get; set; }

/// <summary>
/// 会话Id
/// </summary>
public string SessionId { get; set; }

/// <summary>
/// 客户端Id
/// </summary>
public string ClientId { get; set; }

/// <summary>
/// IP地址
/// </summary>
public string IpAddresses { get; set; }
/// <summary>
/// IP属地
/// </summary>
public string IpRegion { get; set; }

/// <summary>
/// 登录时间
/// </summary>
public DateTime SignedIn { get; set; }

/// <summary>
/// 上次访问时间
/// </summary>
public DateTime? LastAccessed { get; set; }
/// <summary>
/// 过期时间(ms)
/// </summary>
public double? ExpiraIn { get; set; }

public IdentitySessionCacheItem()
{
Expand All @@ -37,7 +60,8 @@ public IdentitySessionCacheItem(
string ipAddresses,
DateTime signedIn,
DateTime? lastAccessed = null,
string ipRegion = null)
string ipRegion = null,
double? expiraIn = null)
{
Device = device;
DeviceInfo = deviceInfo;
Expand All @@ -48,6 +72,7 @@ public IdentitySessionCacheItem(
IpRegion = ipRegion;
SignedIn = signedIn;
LastAccessed = lastAccessed;
ExpiraIn = expiraIn;
}

public static string CalculateCacheKey(string sessionId)
Expand Down

0 comments on commit 36bc767

Please sign in to comment.