private static void ConfigureTokenCache(ITokenCache tokenCache, string tokenCacheFile) { if (!Directory.Exists(Constants.TokenCacheDirectory)) { Directory.CreateDirectory(Constants.TokenCacheDirectory); } string tokenCacheFilePath = Path.Combine(Constants.TokenCacheDirectory, tokenCacheFile); tokenCache.SetBeforeAccess((TokenCacheNotificationArgs args) => { lock (FileLock) { args.TokenCache.DeserializeMsalV3(File.Exists(tokenCacheFilePath) ? TokenCryptographer.DecryptToken(File.ReadAllBytes(tokenCacheFilePath)) : null, shouldClearExistingCache: true); } }); tokenCache.SetAfterAccess((TokenCacheNotificationArgs args) => { lock (FileLock) { if (args.HasStateChanged) { File.WriteAllBytes(tokenCacheFilePath, TokenCryptographer.EncryptToken(args.TokenCache.SerializeMsalV3())); } } }); }
public MSALUserTokenMemoryCache(string clientId, ITokenCache userTokenCache) { this.appId = clientId; userTokenCache.SetBeforeAccess(this.UserTokenCacheBeforeAccessNotification); userTokenCache.SetAfterAccess(this.UserTokenCacheAfterAccessNotification); }
public UserTokenCacheWrapper(ITokenCache userTokenCache, ClaimsPrincipal user) { this.user = user; userTokenCache.SetBeforeAccess(UserTokenCacheBeforeAccessNotification); userTokenCache.SetBeforeWrite(UserTokenCacheBeforeWriteNotification); userTokenCache.SetAfterAccess(UserTokenCacheAfterAccessNotification); }
private static void BindCache(ITokenCache tokenCache, string file) { tokenCache.SetBeforeAccess(notificationArgs => { //Console.BackgroundColor = ConsoleColor.DarkYellow; Console.WriteLine($"SetBeforeAccess invoked for {notificationArgs?.Account?.Username ?? "null"} "); Debug.WriteLine($"SetBeforeAccess invoked for {notificationArgs?.Account?.Username ?? "null"} "); Console.ResetColor(); notificationArgs.TokenCache.DeserializeMsalV3(File.Exists(file) ? File.ReadAllBytes(UserCacheFile) : null); }); tokenCache.SetAfterAccess(notificationArgs => { //Console.BackgroundColor = ConsoleColor.DarkYellow; Console.WriteLine($"SetAfterAccess invoked for {notificationArgs?.Account?.Username ?? "null" } " + $"with HasStateChanges = {notificationArgs.HasStateChanged}"); Debug.WriteLine($"SetAfterAccess invoked for {notificationArgs?.Account?.Username ?? "null" } " + $"with HasStateChanges = {notificationArgs.HasStateChanged}"); Console.ResetColor(); // if the access operation resulted in a cache update if (notificationArgs.HasStateChanged) { // reflect changes in the persistent store File.WriteAllBytes(file, notificationArgs.TokenCache.SerializeMsalV3()); } }); }
/// <summary> /// Configures a token cache using the provide <see cref="IAuthContext"/>. /// </summary> /// <param name="tokenCache">MSAL's token cache to configure.</param> /// <param name="authContext">The <see cref="IAuthContext"/> to get configure an token cache for.</param> private static void ConfigureTokenCache(ITokenCache tokenCache, IAuthContext authContext) { tokenCache.SetBeforeAccess((TokenCacheNotificationArgs args) => { try { _cacheLock.EnterReadLock(); args.TokenCache.DeserializeMsalV3(TokenCacheStorage.GetToken(authContext), shouldClearExistingCache: true); } finally { _cacheLock.ExitReadLock(); } }); tokenCache.SetAfterAccess((TokenCacheNotificationArgs args) => { if (args.HasStateChanged) { try { _cacheLock.EnterWriteLock(); TokenCacheStorage.SetToken(authContext, args.TokenCache.SerializeMsalV3()); } finally { _cacheLock.ExitWriteLock(); } } }); }
/// <summary> /// Gets a singleton instance of the TokenCacheHelper /// </summary> /// <param name="tokenCache">Token Cache</param> /// <returns>token cache helper</returns> public void RegisterCache(ITokenCache tokenCache) { lock (_lockObject) { _userTokenCache = tokenCache ?? throw new ArgumentNullException(nameof(tokenCache)); _userTokenCache.SetBeforeAccess(BeforeAccessNotification); _userTokenCache.SetAfterAccess(AfterAccessNotification); _logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Initializing msal cache"); byte[] data = _store.ReadData(); _logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Read '{data?.Length}' bytes from storage"); if (data != null && data.Length > 0) { try { _logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Deserializing data into memory"); _userTokenCache.DeserializeMsalV3(data); } catch (Exception e) { _logger.TraceEvent(TraceEventType.Warning, /*id*/ 0, $"An exception was encountered while deserializing the data during initialization of {nameof(MsalCacheHelper)} : {e}"); Clear(); } } _logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Done initializing"); } }
/// <summary>Initializes this instance of TokenCacheProvider with essentials to initialize themselves.</summary> /// <param name="tokenCache">The token cache instance of MSAL application</param> /// <param name="httpcontext">The Httpcontext whose Session will be used for caching.This is required by some providers.</param> public void Initialize(ITokenCache tokenCache, HttpContext httpcontext) { _apptokenCache = tokenCache; _apptokenCache.SetBeforeAccess(AppTokenCacheBeforeAccessNotification); _apptokenCache.SetAfterAccess(AppTokenCacheAfterAccessNotification); _apptokenCache.SetBeforeWrite(AppTokenCacheBeforeWriteNotification); }
/// <summary> /// Initializes a token cache (which can be a user token cache or an app token cache) /// </summary> /// <param name="tokenCache">Token cache for which to initialize the serialization</param> public Task InitializeAsync(ITokenCache tokenCache) { tokenCache.SetBeforeAccess(OnBeforeAccess); tokenCache.SetAfterAccess(OnAfterAccess); return(Task.CompletedTask); }
public MSALAppTokenMemoryCache(string clientId, ITokenCache appTokenCache) { this.AppCacheId = clientId + "_AppTokenCache"; appTokenCache.SetBeforeAccess(AppTokenCacheBeforeAccessNotification); appTokenCache.SetAfterAccess(AppTokenCacheAfterAccessNotification); }
/// <summary> /// Registers a token cache to synchronize with on disk storage. /// </summary> /// <param name="tokenCache">Token Cache</param> public void RegisterCache(ITokenCache tokenCache) { if (tokenCache == null) { throw new ArgumentNullException(nameof(tokenCache)); } lock (_lockObject) { _logger.LogInformation($"Registering token cache with on disk storage"); if (_registeredCaches.Contains(tokenCache)) { _logger.LogWarning($"Redundant registration of {nameof(tokenCache)} in {nameof(MsalCacheHelper)}, skipping further registration."); return; } tokenCache.SetBeforeAccess(BeforeAccessNotification); tokenCache.SetAfterAccess(AfterAccessNotification); _logger.LogInformation($"Initializing msal cache"); } _registeredCaches.Add(tokenCache); // Ignore return value, since we already bail if _registeredCaches contains tokenCache earlier _logger.LogInformation($"Done initializing"); }
public ITokenCache EnablePersistence(ITokenCache cache) { this.cache = cache; cache.SetBeforeAccess(BeforeAccessNotification); cache.SetAfterAccess(AfterAccessNotification); return(cache); }
public static void EnableSerialization(ITokenCache tokenCache, String fileName = @"%LOCALAPPDATA%\GraphPowerShellManager\MSALToken.bin") { tokenCache.SetBeforeAccess(BeforeAccessNotification); tokenCache.SetAfterAccess(AfterAccessNotification); CacheFilePath = Environment.ExpandEnvironmentVariables(fileName); }
public void Initialize(ClaimsPrincipal principal, ITokenCache tokenCache) { this.principal = principal; tokenCache.SetBeforeAccess(BeforeAccessNotification); tokenCache.SetAfterAccess(AfterAccessNotification); tokenCache.SetBeforeWrite(BeforeWriteNotification); }
private static IObservable <TokenCacheNotificationArgs> BeforeAccess(this ITokenCache tokenCache) { var subject = new Subject <TokenCacheNotificationArgs>(); tokenCache.SetBeforeAccess(args => subject.OnNext(args)); return(subject.AsObservable()); }
/// <summary> /// Initializes a new instance of the <see cref="MSALAppMemoryTokenCache"/> class. /// </summary> /// <param name="tokenCache">The client's instance of the token cache.</param> /// <param name="clientId">The application's id (Client ID).</param> public MSALAppMemoryTokenCache(ITokenCache tokenCache, string clientId) { this.AppCacheId = clientId + "_AppTokenCache"; tokenCache.SetBeforeAccess(AppTokenCacheBeforeAccessNotification); tokenCache.SetAfterAccess(AppTokenCacheAfterAccessNotification); tokenCache.SetBeforeWrite(AppTokenCacheBeforeWriteNotification); }
/// <summary>Initializes this instance of TokenCacheProvider with essentials to initialize themselves.</summary> /// <param name="tokenCache">The token cache instance of MSAL application</param> /// <param name="httpcontext">The Httpcontext whose Session will be used for caching.This is required by some providers.</param> /// <param name="user">The signed-in user for whom the cache needs to be established. Not needed by all providers.</param> public void Initialize(ITokenCache tokenCache, HttpContext httpcontext, ClaimsPrincipal user) { _signedInUser = user; _userTokenCache = tokenCache; _userTokenCache.SetBeforeAccess(UserTokenCacheBeforeAccessNotification); _userTokenCache.SetAfterAccess(UserTokenCacheAfterAccessNotification); _userTokenCache.SetBeforeWrite(UserTokenCacheBeforeWriteNotification); }
/// <summary>Initializes the cache instance</summary> /// <param name="tokenCache">The ITokenCache passed through the constructor</param> /// <param name="user">The signed-in user for whom the cache needs to be established..</param> private void Initialize(ITokenCache tokenCache, ClaimsPrincipal user) { SignedInUser = user; tokenCache.SetBeforeAccess(UserTokenCacheBeforeAccessNotification); tokenCache.SetAfterAccess(UserTokenCacheAfterAccessNotification); tokenCache.SetBeforeWrite(UserTokenCacheBeforeWriteNotification); }
/// <summary>Initializes this instance of TokenCacheProvider with essentials to initialize themselves.</summary> /// <param name="tokenCache">The token cache instance of MSAL application</param> /// <param name="httpcontext">The Httpcontext whose Session will be used for caching.This is required by some providers.</param> public void Initialize(ITokenCache tokenCache, HttpContext httpcontext) { this.AppCacheId = this.AppId + "_AppTokenCache"; tokenCache.SetBeforeAccess(this.AppTokenCacheBeforeAccessNotification); tokenCache.SetAfterAccess(this.AppTokenCacheAfterAccessNotification); tokenCache.SetBeforeWrite(this.AppTokenCacheBeforeWriteNotification); }
/// <summary> /// Initializes a new instance of the <see cref="MSALAppSessionTokenCache"/> class. /// </summary> /// <param name="tokenCache">The client's instance of the token cache.</param> /// <param name="clientId">The application's id (Client ID).</param> public MSALAppSessionTokenCache(ITokenCache tokenCache, string clientId, HttpContextBase httpcontext) { this.HttpContextInstance = httpcontext; this.AppCacheId = clientId + "_AppTokenCache"; tokenCache.SetBeforeAccess(AppTokenCacheBeforeAccessNotification); tokenCache.SetAfterAccess(AppTokenCacheAfterAccessNotification); tokenCache.SetBeforeWrite(AppTokenCacheBeforeWriteNotification); }
/// <summary> /// Get the user token cache /// </summary> /// <param name="adalV3CacheFileName">File name where the cache is serialized with the ADAL V3 token cache format. Can /// be <c>null</c> if you don't want to implement the legacy ADAL V3 token cache serialization in your MSAL 2.x+ application</param> /// <param name="msalCacheFileName">File name where the cache is serialized with the Unified cache format, common to /// ADAL V4 and MSAL V2 and above, and also across ADAL/MSAL on the same platform. Should not be <c>null</c></param> /// <returns></returns> public static void EnableSerialization(ITokenCache cache, string msalCacheFileName, string adalV3CacheFileName) { usertokenCache = cache; MsalCacheFileName = msalCacheFileName; AdalV3CacheFileName = adalV3CacheFileName; usertokenCache.SetBeforeAccess(BeforeAccessNotification); usertokenCache.SetAfterAccess(AfterAccessNotification); }
public void Initialize(ITokenCache tokenCache, string username) { _userTokenCache = tokenCache; _userTokenCache.SetBeforeAccess(UserTokenCacheBeforeAccessNotification); _userTokenCache.SetAfterAccess(UserTokenCacheAfterAccessNotification); _userTokenCache.SetBeforeWrite(UserTokenCacheBeforeWriteNotification); _signedInUserName = username; }
/// <summary> /// Unregisters a token cache so it no longer synchronizes with on disk storage. /// </summary> public void UnregisterCache(ITokenCache tokenCache) { if (tokenCache == null) { throw new ArgumentNullException(nameof(tokenCache)); } tokenCache.SetBeforeAccess(null); tokenCache.SetAfterAccess(null); }
/// <summary>Initializes the cache instance</summary> /// <param name="tokenCache">The <see cref="ITokenCache"/> passed through the constructor</param> /// <param name="httpcontext">The current <see cref="HttpContext" /></param> /// <param name="user">The signed in user's ClaimPrincipal, could be null. /// If the calling app has it available, then it should pass it themselves.</param> public void Initialize(ITokenCache tokenCache, HttpContext httpcontext, ClaimsPrincipal user) { if (tokenCache == null) { throw new ArgumentNullException(nameof(tokenCache)); } tokenCache.SetBeforeAccess(this.UserTokenCacheBeforeAccessNotification); tokenCache.SetAfterAccess(this.UserTokenCacheAfterAccessNotification); tokenCache.SetBeforeWrite(this.UserTokenCacheBeforeWriteNotification); }
/// <summary> /// Important - do not use SetBefore / SetAfter methods, as these are reserved for app developers /// Instead, use AfterAccess = x, BeforeAccess = y /// </summary> public void Initialize(ITokenCache tokenCache) { if (tokenCache == null) { throw new ArgumentNullException(nameof(tokenCache)); } tokenCache.SetBeforeAccess(OnBeforeAccess); tokenCache.SetAfterAccess(OnAfterAccess); }
/// <summary>Initializes this instance of TokenCacheProvider with essentials to initialize themselves.</summary> /// <param name="tokenCache">The token cache instance of MSAL application</param> /// <param name="httpcontext">The Httpcontext whose Session will be used for caching.This is required by some providers.</param> public void Initialize(ITokenCache tokenCache, HttpContext httpcontext) { _appCacheId = _appId + "_AppTokenCache"; _httpContext = httpcontext; _apptokenCache = tokenCache; _apptokenCache.SetBeforeAccess(AppTokenCacheBeforeAccessNotification); _apptokenCache.SetAfterAccess(AppTokenCacheAfterAccessNotification); _apptokenCache.SetBeforeWrite(AppTokenCacheBeforeWriteNotification); LoadAppTokenCacheFromSession(); }
/// <summary> /// Registers a token cache to synchronize with on disk storage. /// </summary> /// <param name="tokenCache">Token Cache</param> public void RegisterCache(ITokenCache tokenCache) { // OK, we have two nested locks here. We need to maintain a clear ordering to avoid deadlocks. // 1. Use the CrossPlatLock which is respected by all processes and is used around all cache accesses. // 2. Use _lockObject which is used in UnregisterCache, and is needed for all accesses of _registeredCaches. // // Here specifically, we don't want to set this.CacheLock because we're done with the lock by the end of the method. using (var crossPlatLock = CreateCrossPlatLock(_storageCreationProperties)) { lock (_lockObject) { _logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Registering token cache with on disk storage"); if (_registeredCaches.Contains(tokenCache)) { _logger.TraceEvent(TraceEventType.Warning, /*id*/ 0, $"Redundant registration of {nameof(tokenCache)} in {nameof(MsalCacheHelper)}, skipping further registration."); return; } _userTokenCache = tokenCache ?? throw new ArgumentNullException(nameof(tokenCache)); _userTokenCache.SetBeforeAccess(BeforeAccessNotification); _userTokenCache.SetAfterAccess(AfterAccessNotification); _logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Initializing msal cache"); if (_store.HasChanged) { _logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Before access, the store has changed"); byte[] fileData = _store.ReadData(); _logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Read '{fileData?.Length}' bytes from storage"); _cachedStoreData = _store.ReadData(); _logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Read '{_cachedStoreData?.Length}' bytes from storage"); } try { _logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Deserializing data into memory"); _userTokenCache.DeserializeMsalV3(_cachedStoreData); } catch (Exception e) { _logger.TraceEvent(TraceEventType.Warning, /*id*/ 0, $"An exception was encountered while deserializing the data during initialization of {nameof(MsalCacheHelper)} : {e}"); Clear(); } } _registeredCaches.Add(tokenCache); // Ignore return value, since we already bail if _registeredCaches contains tokenCache earlier _logger.TraceEvent(TraceEventType.Information, /*id*/ 0, $"Done initializing"); } }
/// <summary>Initializes the cache instance</summary> /// <param name="tokenCache">The ITokenCache passed through the constructor</param> /// <param name="user">The signed-in user for whom the cache needs to be established..</param> private void Initialize(ITokenCache tokenCache, ClaimsPrincipal user) { this.SignedInUser = user; tokenCache.SetBeforeAccess(UserTokenCacheBeforeAccessNotification); tokenCache.SetAfterAccess(UserTokenCacheAfterAccessNotification); tokenCache.SetBeforeWrite(UserTokenCacheBeforeWriteNotification); if (this.SignedInUser == null) { // No users signed in yet, so we return return; } }
/// <summary> /// Initializes a new instance of the <see cref="MSALAppMemoryTokenCache"/> class. /// </summary> /// <param name="tokenCache">The client's instance of the token cache.</param> /// <param name="clientId">The application's id (Client ID).</param> public MSALAppMemoryTokenCache(ITokenCache tokenCache, string clientId) { AppCacheId = clientId + "_AppTokenCache"; if (AppTokenCache == null) { AppTokenCache = tokenCache; AppTokenCache.SetBeforeAccess(AppTokenCacheBeforeAccessNotification); AppTokenCache.SetAfterAccess(AppTokenCacheAfterAccessNotification); AppTokenCache.SetBeforeWrite(AppTokenCacheBeforeWriteNotification); } LoadAppTokenCacheFromMemory(); }
public SessionTokenStore(ITokenCache tokenCache, HttpContext context, ClaimsPrincipal user) { httpContext = context; if (tokenCache != null) { tokenCache.SetBeforeAccess(BeforeAccessNotification); tokenCache.SetAfterAccess(AfterAccessNotification); } var userId = GetUsersUniqueId(user); tokenCacheKey = $"{userId}_TokenCache"; userCacheKey = $"{userId}_UserCache"; }
/// <summary> /// Registers a token cache to synchronize with the persistent storage. /// </summary> /// <param name="tokenCache">The application token cache, typically referenced as <see cref="IClientApplicationBase.UserTokenCache"/></param> /// <remarks>Call <see cref="UnregisterCache(ITokenCache)"/> to have the given token cache stop syncronizing.</remarks> public void RegisterCache(ITokenCache tokenCache) { if (tokenCache == null) { throw new ArgumentNullException(nameof(tokenCache)); } _logger.LogInformation($"Registering token cache with on disk storage"); // If the token cache was already registered, this operation does nothing tokenCache.SetBeforeAccess(BeforeAccessNotification); tokenCache.SetAfterAccess(AfterAccessNotification); _logger.LogInformation($"Done initializing"); }