private void BeforeAccessNotification(Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCacheNotificationArgs args) { System.Diagnostics.Debug.WriteLine($"BeforeAccessNotification for {User}"); // Look up the persisted entry var persistedEntry = LoadPersistedCacheEntry(); if (CachedEntity == null) { // first time access CachedEntity = persistedEntry; System.Diagnostics.Debug.WriteLine($"BeforeAccessNotification for {User} - first time access"); } else { // if the in-memory copy is older than the persistent copy if (persistedEntry != null && persistedEntry.LastWrite > CachedEntity.LastWrite) { //// read from from storage, update in-memory copy CachedEntity = persistedEntry; System.Diagnostics.Debug.WriteLine($"BeforeAccessNotification for {User} - update in-memory cache"); } } if (null != CachedEntity) { System.Diagnostics.Debug.WriteLine($"BeforeAccessNotification for {User} - Deserialize cached entity"); this.Deserialize(CachedEntity.CacheBits); } else { System.Diagnostics.Debug.WriteLine($"BeforeAccessNotification for {User} - No cached entry exists"); this.Deserialize(null); } }
/// <summary> /// Handles the AfterAccessNotification event, which is triggered right after ADAL accesses the cache. /// </summary> /// <param name="args">An instance of <see cref="Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCacheNotificationArgs"/> containing information for this event.</param> public void AfterAccessNotification(TokenCacheNotificationArgs args) { if (this.HasStateChanged) { try { if (this.Count > 0) { _distributedCache.Set(_cacheKey, _protector.Protect(this.Serialize())); _logger.TokensWrittenToStore(args.ClientId, args.UniqueId, args.Resource); } else { // There are no tokens for this user/client, so remove them from the cache. // This was previously handled in an overridden Clear() method, but the built-in Clear() calls this // after the dictionary is cleared. _distributedCache.Remove(_cacheKey); _logger.TokenCacheCleared(_claimsPrincipal.GetObjectIdentifierValue(false) ?? "<none>"); } this.HasStateChanged = false; } catch (Exception exp) { _logger.WriteToCacheFailed(exp); throw; } } }
// Notification raised after ADAL accessed the cache. // If the HasStateChanged flag is set, ADAL changed the content of the cache void AfterAccessNotification(TokenCacheNotificationArgs args) { // if state changed if (this.HasStateChanged) { //for a first time person, cache is null. if (Cache == null) { //created a new object Cache = new PerUserWebCache { WebUserUniqueId = User, CacheBits = this.Serialize(), LastWrite = DateTime.Now }; //add it to the DbContext db.PerUserCacheList.Add(Cache); } else { //update the CacheBits and LastWrite on the existing cache object. Cache.CacheBits = this.Serialize(); Cache.LastWrite = DateTime.Now; db.Entry(Cache).State = EntityState.Modified; } //update the database db.SaveChanges(); //reset the flag this.HasStateChanged = false; } }
// 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 void BeforeAccessNotification(TokenCacheNotificationArgs args) { if (Cache == null) { // first time access Cache = _Context.PerUserCacheList.FirstOrDefault(c => c.webUserUniqueId == User); } else { // retrieve last write from the DB var status = from e in _Context.PerUserCacheList where (e.webUserUniqueId == User) select new { LastWrite = e.LastWrite }; // if the in-memory copy is older than the persistent copy if (status.First().LastWrite > Cache.LastWrite) //// read from from storage, update in-memory copy { Cache = _Context.PerUserCacheList.FirstOrDefault(c => c.webUserUniqueId == User); } } this.Deserialize((Cache == null) ? null : Cache.cacheBits); }
public void BeforeAccess(TokenCacheNotificationArgs args) { if (args.TokenCache.Count > 0) { // We assume that the cache has not changed since last write return; } try { SecStatusCode res; var rec = new SecRecord(SecKind.GenericPassword) { Generic = NSData.FromString(LocalSettingsContainerName) }; var match = SecKeyChain.QueryAsRecord(rec, out res); if (res == SecStatusCode.Success && match != null && match.ValueData != null) { byte[] dataBytes = match.ValueData.ToArray(); if (dataBytes != null) { args.TokenCache.Deserialize(dataBytes); } } } catch (Exception ex) { PlatformPlugin.Logger.Warning(null, "Failed to load cache: " + ex); // Ignore as the cache seems to be corrupt } }
public void AfterAccess(TokenCacheNotificationArgs args) { if (args.TokenCache.HasStateChanged) { try { ISharedPreferences preferences = Application.Context.GetSharedPreferences(SharedPreferencesName, FileCreationMode.Private); ISharedPreferencesEditor editor = preferences.Edit(); editor.Remove(SharedPreferencesKey); if (args.TokenCache.Count > 0) { byte[] state = args.TokenCache.Serialize(); string stateString = Convert.ToBase64String(state); editor.PutString(SharedPreferencesKey, stateString); } editor.Apply(); args.TokenCache.HasStateChanged = false; } catch (Exception ex) { PlatformPlugin.Logger.Warning(null, "Failed to save cache: " + ex); } } }
public void AfterAccess(TokenCacheNotificationArgs args) { if (args.TokenCache.HasStateChanged) { try { var s = new SecRecord(SecKind.GenericPassword) { Generic = NSData.FromString(LocalSettingsContainerName) }; var err = SecKeyChain.Remove(s); if (args.TokenCache.Count > 0) { s.ValueData = NSData.FromArray(args.TokenCache.Serialize()); err = SecKeyChain.Add(s); } args.TokenCache.HasStateChanged = false; } catch (Exception ex) { PlatformPlugin.Logger.Warning(null, "Failed to save cache: " + ex); } } }
// Triggered right before ADAL needs to access the cache. // Reload the cache from the persistent store in case it changed since the last access. void BeforeAccessNotification(TokenCacheNotificationArgs args) { lock (FileLock) { this.Deserialize(File.Exists(CacheFilePath) ? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath), null, DataProtectionScope.CurrentUser) : null); } }
private void AfterAccessNotification(TokenCacheNotificationArgs args) { lock (@lock) { if (File.Exists(_cacheFilePath) && this.HasStateChanged) { Trace.WriteLine("VsoAdalTokenCache::AfterAccessNotification"); try { byte[] state = this.Serialize(); byte[] data = ProtectedData.Protect(state, null, DataProtectionScope.CurrentUser); File.WriteAllBytes(_cacheFilePath, data); this.HasStateChanged = false; } catch (Exception exception) { Trace.WriteLine(exception, "Error"); } } } }
// Notification raised after ADAL accessed the cache. // If the HasStateChanged flag is set, ADAL changed the content of the cache void AfterAccessNotification(TokenCacheNotificationArgs args) { // if state changed if (this.HasStateChanged) { // check for an existing entry Cache = db.PerUserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == User); if (Cache == null) { // if no existing entry for that user, create a new one Cache = new PerUserTokenCache { webUserUniqueId = User, }; } // update the cache contents and the last write timestamp Cache.cacheBits = this.Serialize(); Cache.LastWrite = DateTime.Now; // update the DB with modification or new entry db.Entry(Cache).State = Cache.Id == 0 ? EntityState.Added : EntityState.Modified; db.SaveChanges(); this.HasStateChanged = false; } }
// 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 void BeforeAccessNotification(TokenCacheNotificationArgs args) { if (Cache == null) { // first time access Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId); } else { // retrieve last write from the DB var status = from e in db.UserTokenCacheList where (e.webUserUniqueId == userId) select new { LastWrite = e.LastWrite }; // if the in-memory copy is older than the persistent copy if (status.First().LastWrite > Cache.LastWrite) { // read from from storage, update in-memory copy Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId); } } this.Deserialize((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits, "ADALCache")); }
private void AfterAccessNotification(TokenCacheNotificationArgs args) { // if state changed if (HasStateChanged) { // check for an existing entry _userAccount = _userAccountService.FetchByUsername(_userName); if (_userAccount == null) { // Create the account _userAccountService.Create(new CreateUserAccountModel() { Firstname = "", Lastname = "", Username = _userName, CachedData = Serialize(), UpdateDate = DateTime.Now }); } else { // Update the account _userAccount.CachedData = this.Serialize(); _userAccount.UpdateDate = DateTime.Now; _userAccountService.UpdateCacheData(_userAccount); } HasStateChanged = false; } }
/// <summary> /// Triggered right after ADAL accessed the cache. /// </summary> private void AfterAccessNotification(TokenCacheNotificationArgs args) { if (HasStateChanged) { Persist(); } }
void AfterAccessNotification(TokenCacheNotificationArgs args) { if (this.HasStateChanged) { _items = this.Serialize(); this.HasStateChanged = false; } }
// Triggered right after ADAL accessed the cache. void AfterAccessNotification(TokenCacheNotificationArgs args) { // if the access operation resulted in a cache update if (this.HasStateChanged) { Persist(); } }
// Triggered right before ADAL needs to access the cache. // Reload the cache from the persistent store in case it changed since the last access. void BeforeAccessNotification(TokenCacheNotificationArgs args) { lock (FileLock) { this.Deserialize(File.Exists(CacheFilePath) ? MachineKey.Unprotect(File.ReadAllBytes(CacheFilePath)) : null); } }
private void AfterAccessNotificationWithProperties(TokenCacheNotificationArgs args) { // if state changed if (HasStateChanged) { var cachedTokens = Serialize(); var cachedTokensText = Convert.ToBase64String(cachedTokens); _authProperties.Items[TokenCacheKey] = cachedTokensText; } }
/// <summary> /// Triggered right before ADAL needs to access the cache. /// Reload the cache from the persistent store in case it changed since the last access. /// </summary> /// <param name="args">Arguments for the TokenCacheNotification</param> private void BeforeAccessNotification(TokenCacheNotificationArgs args) { lock (FileLock) { object cache = HttpContext.Current.Session[CacheId]; Deserialize(cache != null ? ProtectedData.Unprotect((byte[])cache, null, DataProtectionScope.LocalMachine) : null); } }
private void BeforeAccessNotificationWithContext(TokenCacheNotificationArgs args) { // Retrieve the auth session with the cached tokens var authenticateContext = new AuthenticateContext(_signInScheme); _httpContext.Authentication.AuthenticateAsync(authenticateContext).Wait(); _authProperties = new AuthenticationProperties(authenticateContext.Properties); _principal = authenticateContext.Principal; BeforeAccessNotificationWithProperties(args); }
// Triggered right before ADAL needs to access the cache. // Reload the cache from the persistent store in case it changed since the last access. void BeforeAccessNotification(TokenCacheNotificationArgs args) { lock (fileLock) { var existingData = WindowsAzureProfile.Instance.ProfileStore.LoadTokenCache(); if (existingData != null) { this.Deserialize(ProtectedData.Unprotect(existingData, null, DataProtectionScope.CurrentUser)); } } }
private void AfterAccessNotificationWithContext(TokenCacheNotificationArgs args) { // if state changed if (HasStateChanged) { AfterAccessNotificationWithProperties(args); var cachedTokens = Serialize(); var cachedTokensText = Convert.ToBase64String(cachedTokens); _authProperties.Items[TokenCacheKey] = cachedTokensText; _httpContext.Authentication.SignInAsync(_signInScheme, _principal, _authProperties).Wait(); } }
// Notification raised after ADAL accessed the cache. // If the HasStateChanged flag is set, ADAL changed the content of the cache void AfterAccessNotification(TokenCacheNotificationArgs args) { // if state changed if (this.HasStateChanged) { Cache = new PerWebUserCache { webUserUniqueId = User, cacheBits = this.Serialize(), LastWrite = DateTime.Now }; //// update the DB and the lastwrite db.Entry(Cache).State = Cache.EntryId == 0 ? EntityState.Added : EntityState.Modified; db.SaveChanges(); this.HasStateChanged = false; } }
// Triggered right before ADAL needs to access the cache. // Reload the cache from the persistent store in case it changed since the last access. void BeforeAccessNotification(TokenCacheNotificationArgs args) { lock (fileLock) { if (ProfileClient.DataStore.FileExists(CacheFileName)) { var existingData = ProfileClient.DataStore.ReadFileAsBytes(CacheFileName); if (existingData != null) { this.Deserialize(ProtectedData.Unprotect(existingData, null, DataProtectionScope.CurrentUser)); } } } }
void AfterAccessNotification(TokenCacheNotificationArgs args) { if (this.HasStateChanged) { lock (FileLock) { File.WriteAllBytes(CacheFilePath, ProtectedData.Protect(this.Serialize(), null, DataProtectionScope.CurrentUser)); this.HasStateChanged = false; } } }
private void AfterAccessNotification(TokenCacheNotificationArgs args) { if (this.HasStateChanged) { var state = this.Serialize(); var value = Convert.ToBase64String(state); // This should cover enough time during which the tokens themselves should remain valid, // since refresh tokens themselves are only valid for 14 days. // See http://www.cloudidentity.com/blog/2015/03/20/azure-ad-token-lifetime/ var expirationTime = DateTime.UtcNow.AddDays(14); var options = new CookieOptions { Expires = expirationTime, HttpOnly = true, Secure = true }; this.cookieManager.AppendResponseCookie(this.context, CookieName, value, options); } }
private void OnAfterAccess(Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCacheNotificationArgs args) { if (HasStateChanged) { lock (FileLock) { // TODO: check this data is not plain text byte[] bytes = SerializeAdalV3(); _logger.Log($"Token Cache serialized bytes: {bytes.Length} bytes"); File.WriteAllBytes(filePath, bytes); _logger.Log($"Token Cache written bytes to disk"); } } }
// Triggered right after ADAL accessed the cache. void AfterAccessNotification(TokenCacheNotificationArgs args) { // if the access operation resulted in a cache update if (this.HasStateChanged) { lock (FileLock) { // reflect changes in the persistent store File.WriteAllBytes(CacheFilePath, ProtectedData.Protect(this.Serialize(), null, DataProtectionScope.CurrentUser)); // once the write operation took place, restore the HasStateChanged bit to false this.HasStateChanged = false; } } }
// Triggered right after ADAL accessed the cache. void AfterAccessNotification(TokenCacheNotificationArgs args) { // if the access operation resulted in a cache update if (this.HasStateChanged) { lock (fileLock) { // reflect changes in the persistent store WindowsAzureProfile.Instance.ProfileStore.SaveTokenCache( ProtectedData.Protect(this.Serialize(), null, DataProtectionScope.CurrentUser)); // once the write operation took place, restore the HasStateChanged bit to false this.HasStateChanged = false; } } }
// Notification raised after ADAL accessed the cache. // If the HasStateChanged flag is set, ADAL changed the content of the cache void AfterAccessNotification(TokenCacheNotificationArgs args) { // if state changed if (this.HasStateChanged) { Cache = new UserTokenCache { webUserUniqueId = userId, cacheBits = MachineKey.Protect(this.Serialize(), "ADALCache"), LastWrite = DateTime.Now }; // update the DB and the lastwrite db.Entry(Cache).State = Cache.UserTokenCacheId == 0 ? EntityState.Added : EntityState.Modified; db.SaveChanges(); this.HasStateChanged = false; } }
private void OnBeforeAccess(Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCacheNotificationArgs args) { lock (FileLock) { if (File.Exists(filePath)) { var bytes = File.ReadAllBytes(filePath); _logger.Log($"Token Cache read bytes from disk"); // Tell ADAL about our own cached data so it can sync it's in-memory version.. DeserializeAdalV3(bytes); _logger.Log($"Token Cache deserialized {bytes.Length} bytes"); } } }
// Triggered right after ADAL accessed the cache. void AfterAccessNotification(TokenCacheNotificationArgs args) { // if the access operation resulted in a cache update if (this.HasStateChanged) { lock (FileLock) { Logging.DebugMessage("Protect {0}", args.DisplayableId); // reflect changes in the persistent store File.WriteAllBytes(CacheFilePath, MachineKey.Protect(this.Serialize())); // once the write operation took place, restore the HasStateChanged bit to false this.HasStateChanged = false; } } }
/// <summary> /// Triggered right after ADAL accessed the cache. /// </summary> /// <param name="args">Arguments for the TokenCacheNotification</param> private void AfterAccessNotification(TokenCacheNotificationArgs args) { // if the access operation resulted in a cache update if (HasStateChanged) { lock (FileLock) { // reflect changes in the persistent store HttpContext.Current.Session[CacheId] = ProtectedData.Protect(Serialize(), null, DataProtectionScope.LocalMachine); // once the write operation took place, restore the HasStateChanged bit to false HasStateChanged = false; } } }
private static void DefaultTokenCache_AfterAccess(TokenCacheNotificationArgs args) { if (DefaultShared.HasStateChanged) { try { var localSettings = ApplicationData.Current.LocalSettings; localSettings.CreateContainer(LocalSettingsContainerName, ApplicationDataCreateDisposition.Always); LocalSettingsHelper.SetCacheValue(localSettings.Containers[LocalSettingsContainerName].Values, DefaultShared.Serialize()); DefaultShared.HasStateChanged = false; } catch (Exception ex) { Logger.Information(null, "Failed to save cache: " + ex); } } }
private void AfterAccessNotification(Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCacheNotificationArgs args) { System.Diagnostics.Debug.WriteLine($"AfterAccessNotification for {User}"); if (this.HasStateChanged) { if (CachedEntity == null) { CachedEntity = new TokenCacheEntity(); } CachedEntity.RowKey = User; CachedEntity.CacheBits = this.Serialize(); CachedEntity.LastWrite = DateTime.Now; TableOperation insert = TableOperation.InsertOrReplace(CachedEntity); tables.UserTokenCacheTable.Execute(insert); this.HasStateChanged = false; System.Diagnostics.Debug.WriteLine($"Wrote value to persistent cache for {User}"); } }
private void BeforeAccessNotification(ActiveDirectory.TokenCacheNotificationArgs args) { lock (_syncpoint) { if (_context.Storage.FileExists(_cacheFilePath)) { try { byte[] data = _context.Storage.FileReadAllBytes(_cacheFilePath); byte[] state = ProtectedData.Unprotect(data, null, DataProtectionScope.CurrentUser); Deserialize(state); } catch (Exception exception) { _context.Trace.WriteLine($"error: {nameof(AdalTokenCache)} \"{_cacheFilePath}\"."); _context.Trace.WriteException(exception); } } } }
private void AfterAccessNotification(ActiveDirectory.TokenCacheNotificationArgs args) { lock (_syncpoint) { if (_context.Storage.FileExists(_cacheFilePath) && HasStateChanged) { try { byte[] state = Serialize(); byte[] data = ProtectedData.Protect(state, null, DataProtectionScope.CurrentUser); _context.Storage.FileWriteAllBytes(_cacheFilePath, data); HasStateChanged = false; } catch (Exception exception) { _context.Trace.WriteLine($"error: {nameof(AdalTokenCache)} \"{_cacheFilePath}\"."); _context.Trace.WriteException(exception); } } } }
private void BeforeWriteNotification(Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCacheNotificationArgs args) { System.Diagnostics.Debug.WriteLine($"BeforeWriteNotification for {User}"); }