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.

66 lines
2.0 KiB

2 years ago
  1. using Microsoft.Identity.Client;
  2. using System.Threading;
  3. using System.Web;
  4. namespace EasyBL.WEBAPP.TokenStorage
  5. {
  6. public class SessionTokenCache : TokenCache
  7. {
  8. private static ReaderWriterLockSlim sessionLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
  9. string userId = string.Empty;
  10. string cacheId = string.Empty;
  11. HttpContext httpContext = null;
  12. public SessionTokenCache(string userId, HttpContext httpContext)
  13. {
  14. this.userId = userId;
  15. cacheId = userId + "_TokenCache";
  16. this.httpContext = httpContext;
  17. BeforeAccess = BeforeAccessNotification;
  18. AfterAccess = AfterAccessNotification;
  19. Load();
  20. }
  21. public override void Clear(string clientId)
  22. {
  23. base.Clear(clientId);
  24. httpContext.Session.Remove(cacheId);
  25. }
  26. private void Load()
  27. {
  28. sessionLock.EnterReadLock();
  29. Deserialize((byte[])httpContext.Session[cacheId]);
  30. sessionLock.ExitReadLock();
  31. }
  32. private void Persist()
  33. {
  34. sessionLock.EnterReadLock();
  35. // Optimistically set HasStateChanged to false.
  36. // We need to do it early to avoid losing changes made by a concurrent thread.
  37. HasStateChanged = false;
  38. httpContext.Session[cacheId] = Serialize();
  39. sessionLock.ExitReadLock();
  40. }
  41. // Triggered right before ADAL needs to access the cache.
  42. private void BeforeAccessNotification(TokenCacheNotificationArgs args)
  43. {
  44. // Reload the cache from the persistent store in case it changed since the last access.
  45. Load();
  46. }
  47. // Triggered right after ADAL accessed the cache.
  48. private void AfterAccessNotification(TokenCacheNotificationArgs args)
  49. {
  50. // if the access operation resulted in a cache update
  51. if (HasStateChanged)
  52. {
  53. Persist();
  54. }
  55. }
  56. }
  57. }