/// <summary> /// Reads the cache data from the backend database. /// </summary> private void ReadCacheForSignedInUser(TokenCacheNotificationArgs args) { string accountId = httpContextAccesssor.HttpContext.User.GetMsalAccountId(); if (this.InMemoryCache == null) // first time access { this.InMemoryCache = GetLatestUserRecordQuery(accountId).FirstOrDefault(); } else { // retrieve last written record from the DB var lastwriteInDb = GetLatestUserRecordQuery(accountId).Select(n => n.LastWrite).FirstOrDefault(); // if the persisted copy is newer than the in-memory copy if (lastwriteInDb > InMemoryCache.LastWrite) { // read from from storage, update in-memory copy this.InMemoryCache = GetLatestUserRecordQuery(accountId).FirstOrDefault(); } } // Send data to the TokenCache instance args.TokenCache.DeserializeMsalV3((InMemoryCache == null) ? null : this.DataProtector.Unprotect(InMemoryCache.CacheBits), shouldClearExistingCache: true); }
/// <summary> /// Raised AFTER MSAL added the new token in its in-memory copy of the cache. /// This notification is called every time MSAL accessed the cache, not just when a write took place: /// If MSAL's current operation resulted in a cache change, the property TokenCacheNotificationArgs.HasStateChanged will be set to true. /// If that is the case, we call the TokenCache.Serialize() to get a binary blob representing the latest cache content – and persist it. /// </summary> /// <param name="args">Contains parameters used by the MSAL call accessing the cache.</param> private void UserTokenCacheAfterAccessNotification(TokenCacheNotificationArgs args) { string accountId = args.Account?.HomeAccountId?.Identifier; if (string.IsNullOrEmpty(accountId)) { accountId = httpContextAccesssor.HttpContext.User.GetMsalAccountId(); } // if state changed, i.e. new token obtained if (args.HasStateChanged && !string.IsNullOrWhiteSpace(accountId)) { if (this.InMemoryCache == null) { this.InMemoryCache = new UserTokenCache { WebUserUniqueId = accountId }; } this.InMemoryCache.CacheBits = this.DataProtector.Protect(args.TokenCache.SerializeMsalV3()); this.InMemoryCache.LastWrite = DateTime.Now; try { // Update the DB and the lastwrite this.TokenCacheDb.Entry(InMemoryCache).State = InMemoryCache.UserTokenCacheId == 0 ? EntityState.Added : EntityState.Modified; this.TokenCacheDb.SaveChanges(); } catch (DbUpdateConcurrencyException) { // Record already updated on a different thread, so just read the updated record this.ReadCacheForSignedInUser(args); } } }