Exemplo n.º 1
0
        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);
        }
Exemplo n.º 3
0
 public UserTokenCacheWrapper(ITokenCache userTokenCache, ClaimsPrincipal user)
 {
     this.user = user;
     userTokenCache.SetBeforeAccess(UserTokenCacheBeforeAccessNotification);
     userTokenCache.SetBeforeWrite(UserTokenCacheBeforeWriteNotification);
     userTokenCache.SetAfterAccess(UserTokenCacheAfterAccessNotification);
 }
Exemplo n.º 4
0
        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());
                }
            });
        }
Exemplo n.º 5
0
        /// <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();
                    }
                }
            });
        }
Exemplo n.º 6
0
        /// <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");
        }
Exemplo n.º 11
0
 public ITokenCache EnablePersistence(ITokenCache cache)
 {
     this.cache = cache;
     cache.SetBeforeAccess(BeforeAccessNotification);
     cache.SetAfterAccess(AfterAccessNotification);
     return(cache);
 }
Exemplo n.º 12
0
    public static void EnableSerialization(ITokenCache tokenCache, String fileName = @"%LOCALAPPDATA%\GraphPowerShellManager\MSALToken.bin")
    {
        tokenCache.SetBeforeAccess(BeforeAccessNotification);
        tokenCache.SetAfterAccess(AfterAccessNotification);

        CacheFilePath = Environment.ExpandEnvironmentVariables(fileName);
    }
Exemplo n.º 13
0
 public void Initialize(ClaimsPrincipal principal, ITokenCache tokenCache)
 {
     this.principal = principal;
     tokenCache.SetBeforeAccess(BeforeAccessNotification);
     tokenCache.SetAfterAccess(AfterAccessNotification);
     tokenCache.SetBeforeWrite(BeforeWriteNotification);
 }
Exemplo n.º 14
0
        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);
        }
Exemplo n.º 16
0
 /// <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);
 }
Exemplo n.º 17
0
        /// <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);
        }
Exemplo n.º 18
0
        /// <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);
        }
Exemplo n.º 19
0
        /// <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);
        }
Exemplo n.º 20
0
        /// <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);
        }
Exemplo n.º 21
0
        public void Initialize(ITokenCache tokenCache, string username)
        {
            _userTokenCache = tokenCache;
            _userTokenCache.SetBeforeAccess(UserTokenCacheBeforeAccessNotification);
            _userTokenCache.SetAfterAccess(UserTokenCacheAfterAccessNotification);
            _userTokenCache.SetBeforeWrite(UserTokenCacheBeforeWriteNotification);

            _signedInUserName = username;
        }
Exemplo n.º 22
0
        /// <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);
        }
Exemplo n.º 23
0
 /// <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);
 }
Exemplo n.º 24
0
        /// <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);
        }
Exemplo n.º 25
0
        /// <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();
        }
Exemplo n.º 26
0
        /// <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");
            }
        }
Exemplo n.º 27
0
        /// <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;
            }
        }
Exemplo n.º 28
0
        /// <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();
        }
Exemplo n.º 29
0
        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";
        }
Exemplo n.º 30
0
        /// <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");
        }