// Notification raised before ADAL accesses the cache. // This is your chance to update the in-memory copy from the DB, if the in-memory version is stale async void BeforeAccessNotification(TokenCacheNotificationArgs args) { if (Cache == null) { // first time access Cache = await PerWebUserCache.GetCache(new CacheUser(_userObjId, _hostName)); } else { // retrieve last write from the DB var dbCache = await PerWebUserCache.GetCache(new CacheUser(_userObjId, _hostName)); if (dbCache == null) { Cache = await PerWebUserCache.GetCache(new CacheUser(_userObjId, _hostName)); } else { // if the in-memory copy is older than the persistent copy if (dbCache.LastWrite > Cache.LastWrite) { // update in-memory copy Cache = dbCache; } } } this.Deserialize((Cache == null) ? null : Utils.Decrypt(new EncryptedObj(Cache.CacheBits, Cache.Salt))); }
// constructor public AdalCosmosTokenCache(string userObjId, string hostName) { // associate the cache to the current user of the web app _userObjId = userObjId; _hostName = hostName; this.AfterAccess = AfterAccessNotification; this.BeforeAccess = BeforeAccessNotification; // look up the entry in the DB var task = Task.Run(async() => { Cache = await PerWebUserCache.GetCache(new CacheUser(_userObjId, _hostName)); }); task.Wait(); try { // place the entry in memory this.Deserialize((Cache == null) ? null : Utils.Decrypt(new EncryptedObj(Cache.CacheBits, Cache.Salt))); } catch (CryptographicException) { //token is invalid for decryption - delete it and start fresh DeleteItem(Cache); this.Deserialize(null); } catch (Exception ex) { throw ex; } }