コード例 #1
0
        /// <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 AppTokenCacheAfterAccessNotification(TokenCacheNotificationArgs args)
        {
            // if state changed, i.e. new token obtained
            if (args.HasStateChanged && !string.IsNullOrWhiteSpace(_activeClientId))
            {
                if (_inMemoryCache == null)
                {
                    _inMemoryCache = new AppTokenCache
                    {
                        ClientID = _activeClientId
                    };
                }

                _inMemoryCache.CacheBits = _dataProtector.Protect(_apptokenCache.SerializeMsalV3());
                _inMemoryCache.LastWrite = DateTime.Now;

                try
                {
                    // Update the DB and the lastwrite
                    _tokenCacheDb.Entry(_inMemoryCache).State = _inMemoryCache.AppTokenCacheId == 0 ? EntityState.Added : EntityState.Modified;
                    _tokenCacheDb.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    // Record already updated on a different thread, so just read the updated record
                    ReadCacheForSignedInApp();
                }
            }
        }
コード例 #2
0
        /// <summary>
        /// Reads the cache data from the backend database.
        /// </summary>
        private void ReadCacheForSignedInApp()
        {
            if (_inMemoryCache == null) // first time access
            {
                _inMemoryCache = GetLatestAppRecordQuery().FirstOrDefault();
            }
            else
            {
                // retrieve last written record from the DB
                var lastwriteInDb = GetLatestAppRecordQuery().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
                    _inMemoryCache = GetLatestAppRecordQuery().FirstOrDefault();
                }
            }

            // Send data to the TokenCache instance
            _apptokenCache.DeserializeMsalV3((_inMemoryCache == null) ? null : _dataProtector.Unprotect(_inMemoryCache.CacheBits));
        }