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 IDistributedCache _cache; public DistributedCacheTicketStore(IDistributedCache distributedCache) { this._cache = distributedCache; } public async Task StoreAsync(AuthenticationTicket ticket) { var key = KeyPrefix + ticket.Principal.Identity.Name; await RenewAsync(key, ticket); return key; } public Task RenewAsync(string key, AuthenticationTicket 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 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); } } }