You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.2 KiB
68 lines
2.2 KiB
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
using Microsoft.Extensions.Caching.Distributed;
|
|
|
|
namespace Infrastructure.Web.Authentication.Cookies
|
|
{
|
|
public class DistributedCacheTicketStore : ITicketStore
|
|
{
|
|
private const string KeyPrefix = "AuthSessionStore-";
|
|
|
|
private readonly IDistributedCache _cache;
|
|
|
|
public DistributedCacheTicketStore(IDistributedCache distributedCache)
|
|
{
|
|
this._cache = distributedCache;
|
|
}
|
|
|
|
public async Task<string> StoreAsync(AuthenticationTicket ticket)
|
|
{
|
|
if (ticket is null)
|
|
{
|
|
throw new System.ArgumentNullException(nameof(ticket));
|
|
}
|
|
|
|
var key = KeyPrefix + ticket.Principal.Identity.Name;
|
|
await RenewAsync(key, ticket).ConfigureAwait(true);
|
|
return key;
|
|
}
|
|
|
|
public Task RenewAsync(string key, AuthenticationTicket ticket)
|
|
{
|
|
if (ticket is null)
|
|
{
|
|
throw new System.ArgumentNullException(nameof(ticket));
|
|
}
|
|
|
|
var data = _cache.Get(key);
|
|
if (data == null || TicketSerializer.Default.Deserialize(data) != null)
|
|
{
|
|
var ticketBytes = TicketSerializer.Default.Serialize(ticket);
|
|
var options = new DistributedCacheEntryOptions();
|
|
var expiresUtc = ticket.Properties.ExpiresUtc;
|
|
if (expiresUtc.HasValue)
|
|
{
|
|
options.SetAbsoluteExpiration(expiresUtc.Value);
|
|
}
|
|
//options.SetSlidingExpiration(TimeSpan.FromHours(1));
|
|
_cache.Set(key, ticketBytes, options);
|
|
}
|
|
|
|
return Task.FromResult(0);
|
|
}
|
|
|
|
public Task<AuthenticationTicket> RetrieveAsync(string key)
|
|
{
|
|
var data = _cache.Get(key);
|
|
var ticket = data == null ? null : TicketSerializer.Default.Deserialize(data);
|
|
return Task.FromResult(ticket);
|
|
}
|
|
|
|
public Task RemoveAsync(string key)
|
|
{
|
|
_cache.Remove(key);
|
|
return Task.FromResult(0);
|
|
}
|
|
}
|
|
} |