Files
xIdentityService/Providers/XAuthorizationCache.cs
2026-11-15 21:25:33 +03:30

96 lines
2.4 KiB
C#

using System;
using xCommons.Extensions;
using xCommons.Configurations;
using xIdentityService.Constants;
using xIdentityService.Interfaces;
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Caching.Memory;
namespace xIdentityService.Providers
{
/// <summary>
/// Thread-safe local cache; IMemoryCache gives TTL,
/// ConcurrentDictionary gives key tracking for Clear() ...
/// </summary>
public class XAuthorizationCache : IXAuthorizationCache
{
private readonly TimeSpan ttl;
private readonly IMemoryCache cache;
private readonly ConcurrentDictionary<string, byte> keys = new();
private readonly XAppConfiguration appConfiguration;
public XAuthorizationCache(
IMemoryCache cache,
XAppConfiguration appConfiguration
)
{
//
this.cache = cache;
this.appConfiguration = appConfiguration;
ttl = TimeSpan.FromMinutes(appConfiguration.DefaultCacheTtlMinutes);
}
public bool TryGetPolicy(
string name,
out AuthorizationPolicy policy
)
{
//
policy = null;
//
var result =
!name.IsNullOrEmpty() &&
cache.TryGetValue(Key(name), out policy);
return result;
}
public void SetPolicy(
string name,
AuthorizationPolicy policy
)
{
//
if (name.IsNullOrEmpty() || policy.IsNull())
{
return;
}
//
cache.Set(Key(name), policy, ttl);
keys[Key(name)] = 0;
}
public void RemovePolicy(string name)
{
//
if (name.IsNullOrEmpty())
{
return;
}
//
cache.Remove(Key(name));
keys.TryRemove(Key(name), out _);
}
public void Clear()
{
//
foreach (var key in keys.Keys)
{
cache.Remove(key);
}
//
keys.Clear();
}
//
#region Private ...
private static string Key(string name) =>
XIdentityServiceConstants.PolicyCacheKeyPrefix + name.ToNormalString();
#endregion
}
}