/// <summary>
 /// Constructs a JwtAssertionTokenClient with specified options
 /// </summary>
 /// <param name="options">Token client options</param>
 public JwtAssertionTokenClient(TokenClientOptions options)
 {
     ValidateOptions(options);
     _cache = options.Cache ?? DefaultTokenCache.Value;
     _internalClient = new PrivateKeyJwtClientCredentialsTokenClient(options);
     _partialCacheKey = string.Join("|", options.TokenEndpointUrl, options.ClientId, options.Certificate.Thumbprint);
 }
 /// <summary>
 /// Constructs a JwtAssertionTokenClient with default (in-memory) cache
 /// </summary>
 /// <param name="tokenEndpointUrl">Authorization Server token endpoint</param>
 /// <param name="clientId">OAuth2 client_id</param>
 /// <param name="certificate">Certificate used for signing JWT client assertion (must have private key)</param>
 /// <param name="cache">Token cache</param>
 public JwtAssertionTokenClient(string tokenEndpointUrl, string clientId, X509Certificate2 certificate, ITokenCache cache)
     : this(new TokenClientOptions()
     {
         TokenEndpointUrl = tokenEndpointUrl,
         ClientId = clientId,
         Certificate = certificate,
         Cache = cache
     })
 {
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MSALPerUserMemoryTokenCache"/> class.
 /// </summary>
 /// <param name="tokenCache">The client's instance of the token cache.</param>
 /// <param name="user">The signed-in user for whom the cache needs to be established.</param>
 public MSALPerUserMemoryTokenCache(ITokenCache tokenCache, ClaimsPrincipal user)
 {
     this.Initialize(tokenCache, user);
 }
 public void Bind(ITokenCache tokenCache)
 {
     tokenCache.SetBeforeAccess(BeforeAccessNotification);
     tokenCache.SetAfterAccess(AfterAccessNotification);
 }
 public RefreshTokenRetriever(ITokenCache tokenCache)
 {
     tokenCache.SetAfterAccess(AfterAccessHandler);
 }
Ejemplo n.º 6
0
 public MSALPerUserSessionTokenCache(ITokenCache tokenCache, HttpContextBase httpcontext, ClaimsPrincipal user)
 {
     this.Initialize(tokenCache, httpcontext, user);
 }
Ejemplo n.º 7
0
 public void RegisterCallbacks(ITokenCache cache)
 {
     _ = cache ?? throw new ArgumentNullException(nameof(cache));
     cache.SetBeforeAccess(OnSetBeforeAccess);
     cache.SetAfterAccess(OnSetAfterAccess);
 }
Ejemplo n.º 8
0
 private void Persist(string key, ITokenCache tokenCache)
 {
     _cache.Set(key, tokenCache.SerializeMsalV3(), DateTimeOffset.Now.AddHours(12));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MSALMemoryTokenCache"/> class.
 /// </summary>
 /// <param name="tokenCache">The client's instance of the token cache.</param>
 public MSALMemoryTokenCache(ITokenCache tokenCache)
 {
     Initialize(tokenCache);
 }
Ejemplo n.º 10
0
 public static void Initialize(ITokenCache tokenCache)
 {
     tokenCache.SetBeforeAccessAsync(BeforeAccessAsync);
     tokenCache.SetAfterAccessAsync(AfterAccessAsync);
 }
Ejemplo n.º 11
0
 /// <summary>Initializes a new instance of the <see cref="OAuthTokenService" /> class.</summary>
 /// <param name="client">The client.</param>
 /// <param name="tokenCache">The token cache.</param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="client"/> or <paramref name="tokenCache"/> is null.
 /// </exception>
 public OAuthTokenService(IOAuthClient client, ITokenCache <OAuthOptions, Token> tokenCache)
 {
     _client     = client ?? throw new ArgumentNullException(nameof(client));
     _tokenCache = tokenCache ?? throw new ArgumentNullException(nameof(tokenCache));
 }
Ejemplo n.º 12
0
 protected override void Given()
 {
     _tokenCache = ApplicationContext.Container.Resolve <ITokenCache>();
 }
Ejemplo n.º 13
0
 internal TokenCacheHelper(ITokenCache tokenCache, string fileName)
 {
     CacheFilePath = fileName;
     tokenCache.SetBeforeAccess(BeforeAccessNotification);
     tokenCache.SetAfterAccess(AfterAccessNotification);
 }
 private static IObservable <TokenCacheNotificationArgs> WriteStorage(this ITokenCache tokenCache, Func <IObjectSpace> objectSpaceFactory, Guid userId)
 => tokenCache.AfterAccess().Select(args => {
 private static IObservable <TokenCacheNotificationArgs> WriteStorage(this ITokenCache tokenCache, string cacheFilePath) => tokenCache.AfterAccess()
 .Select(args => {
     var bytes = ProtectedData.Protect(args.TokenCache.SerializeMsalV3(), null, DataProtectionScope.CurrentUser);
     File.WriteAllBytes(cacheFilePath, bytes);
     return(args);
 });
Ejemplo n.º 16
0
 public void EnableSerialization(ITokenCache tokenCache)
 {
     Ensure.ParamNotNull(tokenCache, nameof(tokenCache));
     tokenCache.SetBeforeAccess(BeforeAccessNotification);
     tokenCache.SetAfterAccess(AfterAccessNotification);
 }
Ejemplo n.º 17
0
 public void Initialize(ITokenCache tokenCache)
 {
     tokenCache.SetBeforeAccess(BeforeAccessNotification);
     tokenCache.SetAfterAccess(AfterAccessNotification);
     tokenCache.SetBeforeWrite(BeforeWriteNotification);
 }
 /// <summary>Initializes the cache instance</summary>
 /// <param name="tokenCache">The ITokenCache passed through the constructor</param>
 private void Initialize(ITokenCache tokenCache)
 {
     tokenCache.SetBeforeAccess(TokenCacheBeforeAccessNotification);
     tokenCache.SetAfterAccess(TokenCacheAfterAccessNotification);
 }
Ejemplo n.º 19
0
        private void Load(string key, ITokenCache tokenCache)
        {
            var data = (byte[])_cache.Get(key);

            tokenCache.DeserializeMsalV3(data);
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Unregisters a token cache so it no longer synchronizes with on disk storage.
 /// </summary>
 /// <param name="tokenCache"></param>
 public virtual void UnregisterCache(ITokenCache tokenCache)
 {
     _helper.UnregisterCache(tokenCache);
 }
Ejemplo n.º 21
0
 public static void Initialize(string key, IDistributedCache distributedCache, ITokenCache tokenCache)
 {
     _key        = key;
     _cache      = distributedCache;
     _tokenCache = tokenCache;
     _tokenCache.SetBeforeAccessAsync(OnBeforeAccessHandler);
     _tokenCache.SetAfterAccessAsync(OnAfterAccessHandler);
 }
 /// <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)
 {
     tokenCache.SetBeforeAccess(this.AppTokenCacheBeforeAccessNotification);
     tokenCache.SetAfterAccess(this.AppTokenCacheAfterAccessNotification);
     tokenCache.SetBeforeWrite(this.AppTokenCacheBeforeWriteNotification);
 }
Ejemplo n.º 23
0
        //public static implicit operator ITokenCache(TokenCacheBase b)
        //{
        //    return b.GetCacheInstance();
        //}

        public void SetCacheInstance(ITokenCache cache)
        {
            this.cache = cache;
            GetCacheInstance();
        }
 /// <summary>
 /// Initializes the token cache serialization.
 /// </summary>
 /// <param name="tokenCache">Token cache to serialize/deserialize.</param>
 /// <returns>A <see cref="Task"/> that represents a completed initialization operation.</returns>
 public Task InitializeAsync(ITokenCache tokenCache)
 {
     Initialize(tokenCache);
     return(Task.CompletedTask);
 }
 /// <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)
 {
     tokenCache.SetBeforeAccess(this.UserTokenCacheBeforeAccessNotification);
     tokenCache.SetAfterAccess(this.UserTokenCacheAfterAccessNotification);
     tokenCache.SetBeforeWrite(this.UserTokenCacheBeforeWriteNotification);
 }
 public ForgeHandler(IOptions <ForgeConfiguration> configuration)
 {
     this.configuration      = configuration ?? throw new ArgumentNullException(nameof(configuration));
     this.TokenCache         = new TokenCache();
     this.resiliencyPolicies = GetResiliencyPolicies(GetDefaultTimeout());
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MSALPerUserMemoryTokenCache"/> class.
 /// </summary>
 /// <param name="tokenCache">The client's instance of the token cache.</param>
 public MSALPerUserMemoryTokenCache(ITokenCache tokenCache)
 {
     this.Initialize(tokenCache, ClaimsPrincipal.Current);
 }
Ejemplo n.º 28
0
 /// <summary>Initializes this instance of TokenCacheProvider with essentials to initialize themselves.</summary>
 /// <param name="tokenCache">The token cache instance of MSAL application</param>
 public async Task InitializeAsync(ITokenCache tokenCache)
 {
     await InitializeAsync(tokenCache, true).ConfigureAwait(false);
 }
Ejemplo n.º 29
0
 public void EnableSerialization(ITokenCache tokenCache)
 {
     tokenCache.SetBeforeAccess(BeforeAccessNotification);
     tokenCache.SetAfterAccess(AfterAccessNotification);
 }
        /// <summary>
        /// Constructor with Parameter cacheFilePath
        /// </summary>
        /// <param name="cacheFilePath"></param>
        /// <param name="tokenCache"></param>
        public CdsServiceClientTokenCache(ITokenCache tokenCache, string cacheFilePath)
        {
            logEntry = new CdsTraceLogger();

            //If cacheFilePath is provided
            if (!string.IsNullOrEmpty(cacheFilePath))
            {
                _cacheFilePath = cacheFilePath;

                // Register MSAL event handlers.
                tokenCache.SetBeforeAccess(BeforeAccessNotification);
                tokenCache.SetAfterAccess(AfterAccessNotification);

                // Need to revist this for adding support for other cache providers:
                // https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-net-token-cache-serialization

                //				// Try to encrypt some data to test if Protect is available.
                //				try
                //				{
                //#pragma warning disable CS0618 // Type or member is obsolete
                //					ProtectedData.Protect(this.Serialize(), null, DataProtectionScope.CurrentUser);
                //#pragma warning restore CS0618 // Type or member is obsolete
                //				}
                //				catch (Exception ex)
                //				{
                //					_UseLocalFileEncryption = false;
                //					logEntry.Log("Encryption System not available in this environment", TraceEventType.Warning, ex);
                //				}


                // Create token cache file if one does not already exist.
                if (!File.Exists(_cacheFilePath))
                {
                    string directoryName = Path.GetDirectoryName(_cacheFilePath);

                    if (!Directory.Exists(directoryName))
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    //File.Create(string) returns an instance of the FileStream class. You need to use Close() method
                    //in order to close it and release resources which are using
                    try
                    {
                        File.Create(_cacheFilePath).Close();
                        // Encrypt the file
                        try
                        {
                            // user is using a specified file directory... encrypt file to user using Machine / FS Locking.
                            // this will lock / prevent users other then the current user from accessing this file.
                            FileInfo fi = new FileInfo(_cacheFilePath);
                            if (_UseLocalFileEncryption)
                            {
                                fi.Encrypt();
                            }
                        }
                        catch (IOException)
                        {
                            // This can happen when a certificate system on the host has failed.
                            // usually this can be fixed with the steps in this article : http://support.microsoft.com/kb/937536
                            //logEntry.Log(string.Format("{0}\r\nException Details : {1}", "Failed to Encrypt Configuration File!", encrEX), TraceEventType.Error);
                            //logEntry.Log("This problem may be related to a domain certificate in windows being out of sync with the domain, please read http://support.microsoft.com/kb/937536");
                        }
                        catch (Exception)
                        {
                            //logEntry.Log(string.Format("Failed to Encrypt Configuration File!", genEX), TraceEventType.Error);
                        }
                    }
                    catch (Exception exception)
                    {
                        logEntry.Log(string.Format("{0}\r\nException Details : {1}", "Error occurred in CdsServiceClientTokenCache.CdsServiceClientTokenCache(). ", exception), TraceEventType.Error);
                    }
                }

                //// Register ADAL event handlers.
                //this.AfterAccess = AfterAccessNotification;
                //this.BeforeAccess = BeforeAccessNotification;

//				lock (_fileLocker)
//				{
//					try
//					{
//						// Read token from the persistent store and supply it to ADAL's in memory cache.
//						if (_UseLocalFileEncryption)
//#pragma warning disable CS0618 // Type or member is obsolete
//							this.Deserialize(File.Exists(_cacheFilePath) && File.ReadAllBytes(_cacheFilePath).Length != 0
//								? ProtectedData.Unprotect(File.ReadAllBytes(_cacheFilePath), null, DataProtectionScope.CurrentUser)
//								: null);
//#pragma warning restore CS0618 // Type or member is obsolete
//						else
//#pragma warning disable CS0618 // Type or member is obsolete
//							this.Deserialize(File.Exists(_cacheFilePath) && File.ReadAllBytes(_cacheFilePath).Length != 0
//								? File.ReadAllBytes(_cacheFilePath) : null);
//#pragma warning restore CS0618 // Type or member is obsolete
//					}
//					catch (Exception ex)
//					{
//						// Failed to access Local token cache file..
//						// Delete it.
//						logEntry.Log("Failed to access token cache file, resetting the token cache file", TraceEventType.Warning, ex);
//						Clear(_cacheFilePath);
//					}
//				}
            }
        }
Ejemplo n.º 31
0
 public MSALAppTokenMemoryCache(ITokenCache appTokenCache)
 {
     appTokenCache.SetBeforeAccess(AppTokenCacheBeforeAccessNotification);
     appTokenCache.SetAfterAccess(AppTokenCacheAfterAccessNotification);
 }
Ejemplo n.º 32
0
 public static IObservable <TokenCacheNotificationArgs> SynchStorage(this ITokenCache tokenCache, string cacheFilePath)
 => tokenCache.ReadStorage(cacheFilePath).Merge(tokenCache.WriteStorage(cacheFilePath));