IwbAuthenticationSessionStore.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Threading.Tasks;
  3. using Microsoft.Extensions.Caching.Memory;
  4. using Microsoft.Owin.Security;
  5. using Microsoft.Owin.Security.Cookies;
  6. namespace IwbZero.Zero.Configuration
  7. {
  8. public class IwbAuthenticationSessionStore : IAuthenticationSessionStore
  9. {
  10. private const string KeyPrefix = "IWB-";
  11. private readonly IMemoryCache _cache;
  12. public IwbAuthenticationSessionStore()
  13. {
  14. _cache = new MemoryCache(new MemoryCacheOptions());
  15. }
  16. public async Task<string> StoreAsync(AuthenticationTicket ticket)
  17. {
  18. var key = KeyPrefix + Guid.NewGuid().ToString("N");
  19. await RenewAsync(key, ticket);
  20. return key;
  21. }
  22. public Task RenewAsync(string key, AuthenticationTicket ticket)
  23. {
  24. var options = new MemoryCacheEntryOptions();
  25. var expiresUtc = ticket.Properties.ExpiresUtc;
  26. if (expiresUtc.HasValue)
  27. {
  28. options.SetAbsoluteExpiration(expiresUtc.Value);
  29. }
  30. options.SetSlidingExpiration(TimeSpan.FromHours(1));
  31. _cache.Set(key, ticket, options);
  32. return Task.FromResult(0);
  33. }
  34. public Task<AuthenticationTicket> RetrieveAsync(string key)
  35. {
  36. _cache.TryGetValue(key, out AuthenticationTicket ticket);
  37. return Task.FromResult(ticket);
  38. }
  39. public Task RemoveAsync(string key)
  40. {
  41. _cache.Remove(key);
  42. return Task.FromResult(0);
  43. }
  44. }
  45. }