Exemple #1
0
        public AuthenticationRequestParameters CreateAuthenticationRequestParameters(
            string authority,
            IEnumerable <string> scopes    = null,
            ITokenCacheInternal tokenCache = null,
            IAccount account = null,
            IDictionary <string, string> extraQueryParameters = null,
            string claims          = null,
            ApiEvent.ApiIds apiId  = ApiEvent.ApiIds.None,
            bool validateAuthority = false)
        {
            scopes     = scopes ?? TestConstants.s_scope;
            tokenCache = tokenCache ?? new TokenCache(ServiceBundle, false);

            var commonParameters = new AcquireTokenCommonParameters
            {
                Scopes = scopes ?? TestConstants.s_scope,
                ExtraQueryParameters = extraQueryParameters ?? new Dictionary <string, string>(),
                Claims = claims,
                ApiId  = apiId
            };

            return(new AuthenticationRequestParameters(
                       ServiceBundle,
                       tokenCache,
                       commonParameters,
                       new RequestContext(ServiceBundle, Guid.NewGuid()))
            {
                Account = account,
                Authority = Authority.CreateAuthority(authority, validateAuthority)
            });
        }
        public AuthenticationRequestParameters CreateAuthenticationRequestParameters(
            string authority,
            SortedSet <string> scopes,
            ITokenCacheInternal tokenCache = null,
            IAccount account = null,
            IDictionary <string, string> extraQueryParameters = null,
            string claims = null)
        {
            var commonParameters = new AcquireTokenCommonParameters
            {
                Scopes = scopes ?? MsalTestConstants.Scope,
                ExtraQueryParameters = extraQueryParameters ?? new Dictionary <string, string>(),
                Claims = claims
            };

            return(new AuthenticationRequestParameters(
                       ServiceBundle,
                       tokenCache,
                       commonParameters,
                       new RequestContext(ServiceBundle, Guid.NewGuid()))
            {
                Account = account,
                Authority = Authority.CreateAuthority(ServiceBundle, authority)
            });
        }
Exemple #3
0
        async Task ITokenCacheInternal.RemoveAccountAsync(IAccount account, RequestContext requestContext)
        {
            await _semaphoreSlim.WaitAsync().ConfigureAwait(false);

            try
            {
                requestContext.Logger.Info("Removing user from cache..");

                ITokenCacheInternal tokenCacheInternal = this;

                try
                {
                    if (tokenCacheInternal.IsTokenCacheSerialized())
                    {
                        var args = new TokenCacheNotificationArgs(
                            this,
                            ClientId,
                            account,
                            true,
                            tokenCacheInternal.IsApplicationCache,
                            tokenCacheInternal.HasTokensNoLocks(),
                            account.HomeAccountId.Identifier);

                        await tokenCacheInternal.OnBeforeAccessAsync(args).ConfigureAwait(false);

                        await tokenCacheInternal.OnBeforeWriteAsync(args).ConfigureAwait(false);
                    }

                    tokenCacheInternal.RemoveMsalAccountWithNoLocks(account, requestContext);
                    if (ServiceBundle.Config.LegacyCacheCompatibilityEnabled)
                    {
                        RemoveAdalUser(account);
                    }
                }
                finally
                {
                    if (tokenCacheInternal.IsTokenCacheSerialized())
                    {
                        var afterAccessArgs = new TokenCacheNotificationArgs(
                            this,
                            ClientId,
                            account,
                            true,
                            tokenCacheInternal.IsApplicationCache,
                            hasTokens: tokenCacheInternal.HasTokensNoLocks(),
                            account.HomeAccountId.Identifier);

                        await tokenCacheInternal.OnAfterAccessAsync(afterAccessArgs).ConfigureAwait(false);
                    }
                }
            }
            finally
            {
#pragma warning disable CS0618 // Type or member is obsolete
                HasStateChanged = false;
#pragma warning restore CS0618 // Type or member is obsolete

                _semaphoreSlim.Release();
            }
        }
Exemple #4
0
        public AuthenticationRequestParameters CreateAuthenticationRequestParameters(
            string authority,
            IEnumerable <string> scopes,
            ITokenCacheInternal tokenCache,
            IAccount account = null,
            IDictionary <string, string> extraQueryParameters = null,
            string claims         = null,
            ApiEvent.ApiIds apiId = ApiEvent.ApiIds.None)
        {
            if (tokenCache == null)
            {
                throw new ArgumentNullException(nameof(tokenCache));
            }

            var commonParameters = new AcquireTokenCommonParameters
            {
                Scopes = scopes ?? TestConstants.s_scope,
                ExtraQueryParameters = extraQueryParameters ?? new Dictionary <string, string>(),
                Claims = claims,
                ApiId  = apiId
            };

            return(new AuthenticationRequestParameters(
                       ServiceBundle,
                       tokenCache,
                       commonParameters,
                       new RequestContext(ServiceBundle, Guid.NewGuid()))
            {
                Account = account,
                Authority = Authority.CreateAuthority(authority)
            });
        }
 public CacheSessionManager(
     ITokenCacheInternal tokenCacheInternal,
     AuthenticationRequestParameters requestParams)
 {
     TokenCacheInternal = tokenCacheInternal ?? throw new ArgumentNullException(nameof(tokenCacheInternal));
     _requestParams     = requestParams ?? throw new ArgumentNullException(nameof(requestParams));
 }
        private async Task ValidateCacheEntitiesEnvironmentAsync(ITokenCacheInternal cache, string expectedEnvironment)
        {
            ICoreLogger logger = Substitute.For<ICoreLogger>();
            IEnumerable<Client.Cache.Items.MsalAccessTokenCacheItem> accessTokens = await cache.GetAllAccessTokensAsync(true).ConfigureAwait(false);
            foreach (Client.Cache.Items.MsalAccessTokenCacheItem at in accessTokens)
            {
                Assert.AreEqual(expectedEnvironment, at.Environment);
            }

            IEnumerable<Client.Cache.Items.MsalRefreshTokenCacheItem> refreshTokens = await cache.GetAllRefreshTokensAsync(true).ConfigureAwait(false);
            foreach (Client.Cache.Items.MsalRefreshTokenCacheItem rt in refreshTokens)
            {
                Assert.AreEqual(expectedEnvironment, rt.Environment);
            }

            IEnumerable<Client.Cache.Items.MsalIdTokenCacheItem> idTokens = await cache.GetAllIdTokensAsync(true).ConfigureAwait(false);
            foreach (Client.Cache.Items.MsalIdTokenCacheItem id in idTokens)
            {
                Assert.AreEqual(expectedEnvironment, id.Environment);
            }

            IEnumerable<Client.Cache.Items.MsalAccountCacheItem> accounts = await cache.GetAllAccountsAsync().ConfigureAwait(false);
            foreach (Client.Cache.Items.MsalAccountCacheItem account in accounts)
            {
                Assert.AreEqual(expectedEnvironment, account.Environment);
            }

            IDictionary<AdalTokenCacheKey, AdalResultWrapper> adalCache =
                AdalCacheOperations.Deserialize(logger, cache.LegacyPersistence.LoadCache());

            foreach (KeyValuePair<AdalTokenCacheKey, AdalResultWrapper> kvp in adalCache)
            {
                Assert.AreEqual(expectedEnvironment, new Uri(kvp.Key.Authority).Host);
            }
        }
Exemple #7
0
        public AuthenticationRequestParameters(
            IServiceBundle serviceBundle,
            ITokenCacheInternal tokenCache,
            AcquireTokenCommonParameters commonParameters,
            RequestContext requestContext)
        {
            _commonParameters = commonParameters;

            Authority = Authority.CreateAuthorityForRequest(serviceBundle.Config.AuthorityInfo, commonParameters.AuthorityOverride);

            ClientId            = serviceBundle.Config.ClientId;
            CacheSessionManager = new CacheSessionManager(tokenCache, this, serviceBundle.TelemetryManager);
            Scope           = ScopeHelper.CreateSortedSetFromEnumerable(commonParameters.Scopes);
            RedirectUri     = new Uri(serviceBundle.Config.RedirectUri);
            RequestContext  = requestContext;
            IsBrokerEnabled = serviceBundle.Config.IsBrokerEnabled;

            // Set application wide query parameters.
            ExtraQueryParameters = serviceBundle.Config.ExtraQueryParameters ?? new Dictionary <string, string>();

            // Copy in call-specific query parameters.
            if (commonParameters.ExtraQueryParameters != null)
            {
                foreach (KeyValuePair <string, string> kvp in commonParameters.ExtraQueryParameters)
                {
                    ExtraQueryParameters[kvp.Key] = kvp.Value;
                }
            }
        }
 public static void AddRefreshTokenCacheItem(this ITokenCacheInternal tokenCache, MsalRefreshTokenCacheItem accessTokenItem)
 {
     lock (_lock)
     {
         tokenCache.Accessor.SaveRefreshToken(accessTokenItem);
     }
 }
Exemple #9
0
            public AuthenticationRequestParameters CreateRequestParams(
                ITokenCacheInternal cache,
                SortedSet <string> scopes,
                IDictionary <string, string> extraQueryParams = null,
                string claims = null,
                AuthorityInfo authorityOverride = null)
            {
                var commonParameters = new AcquireTokenCommonParameters
                {
                    Scopes = scopes ?? TestConstants.s_scope,
                    ExtraQueryParameters = extraQueryParams,
                    Claims            = claims,
                    AuthorityOverride = authorityOverride
                };

                var parameters = new AuthenticationRequestParameters(
                    ServiceBundle,
                    cache,
                    commonParameters,
                    new RequestContext(ServiceBundle, Guid.NewGuid()))
                {
                    Account = new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null),
                };

                return(parameters);
            }
 // todo add id token
 internal MsalUserAccessTokenControl(ITokenCacheInternal cache, MsalAccessTokenCacheItem item) : this()
 {
     _cache = cache;
     _item  = item;
     accessTokenAuthorityLabel.Text = _item.Environment;
     accessTokenScopesLabel.Text    = string.Join(" ", _item.ScopeSet.ToArray());
     expiresOnLabel.Text            = _item.ExpiresOn.ToString(CultureInfo.CurrentCulture);
 }
 // todo add id token
 internal MsalUserAccessTokenControl(ITokenCacheInternal cache, MsalAccessTokenCacheItem item) : this()
 {
     _cache = cache;
     _item  = item;
     accessTokenAuthorityLabel.Text = _item.Authority;
     accessTokenScopesLabel.Text    = _item.NormalizedScopes;
     expiresOnLabel.Text            = _item.ExpiresOn.ToString(CultureInfo.CurrentCulture);
 }
        public async Task ApplicationGrantIntegrationTestAsync()
        {
            var confidentialClient = ConfidentialClientApplicationBuilder
                                     .Create(ClientId).WithAuthority(new Uri(Authority), true).WithRedirectUri(RedirectUri)
                                     .WithClientSecret(_password).BuildConcrete();

            var res = await confidentialClient
                      .AcquireTokenForClient(_msalScopes)
                      .ExecuteAsync(CancellationToken.None)
                      .ConfigureAwait(false);

            ITokenCacheInternal userCache = confidentialClient.UserTokenCacheInternal;
            ITokenCacheInternal appCache  = confidentialClient.AppTokenCacheInternal;

            Assert.IsNotNull(res);
            Assert.IsNotNull(res.AccessToken);
            Assert.IsNull(res.IdToken);
            Assert.IsNull(res.Account);

            // make sure user cache is empty
            Assert.AreEqual(0, userCache.Accessor.GetAllAccessTokens().Count());
            Assert.AreEqual(0, userCache.Accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(0, userCache.Accessor.GetAllIdTokens().Count());
            Assert.AreEqual(0, userCache.Accessor.GetAllAccounts().Count());

            // make sure nothing was written to legacy cache
            Assert.IsNull(userCache.LegacyPersistence.LoadCache());

            // make sure only AT entity was stored in the App msal cache
            Assert.AreEqual(1, userCache.Accessor.GetAllAccessTokens().Count());
            Assert.AreEqual(0, appCache.Accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(0, appCache.Accessor.GetAllIdTokens().Count());
            Assert.AreEqual(0, appCache.Accessor.GetAllAccounts().Count());

            Assert.IsNull(appCache.LegacyPersistence.LoadCache());

            // passing empty password to make sure that AT returned from cache
            confidentialClient = ConfidentialClientApplicationBuilder
                                 .Create(ClientId)
                                 .WithAuthority(new Uri(Authority), true)
                                 .WithRedirectUri(RedirectUri)
                                 .WithClientSecret("wrong_password")
                                 .BuildConcrete();

            ((ITokenCacheSerializer)confidentialClient.AppTokenCacheInternal).DeserializeMsalV3(((ITokenCacheSerializer)appCache).SerializeMsalV3());
            ((ITokenCacheSerializer)confidentialClient.UserTokenCacheInternal).DeserializeMsalV3(((ITokenCacheSerializer)userCache).SerializeMsalV3());

            res = await confidentialClient
                  .AcquireTokenForClient(_msalScopes)
                  .ExecuteAsync(CancellationToken.None)
                  .ConfigureAwait(false);

            Assert.IsNotNull(res);
            Assert.IsNotNull(res.AccessToken);
            Assert.IsNull(res.IdToken);
            Assert.IsNull(res.Account);
        }
        public static void ExpireAccessTokens(ITokenCacheInternal tokenCache)
        {
            var allAccessTokens = tokenCache.Accessor.GetAllAccessTokens();

            foreach (MsalAccessTokenCacheItem atItem in allAccessTokens)
            {
                ExpireAndSaveAccessToken(tokenCache, atItem);
            }
        }
 public CacheSessionManager(
     ITokenCacheInternal tokenCacheInternal,
     AuthenticationRequestParameters requestParams,
     ITelemetryManager telemetryManager)
 {
     TokenCacheInternal = tokenCacheInternal;
     _requestParams     = requestParams ?? throw new ArgumentNullException(nameof(requestParams));
     _telemetryManager  = telemetryManager ?? throw new ArgumentNullException(nameof(telemetryManager));
 }
        internal override async Task <AuthenticationRequestParameters> CreateRequestParametersAsync(
            AcquireTokenCommonParameters commonParameters,
            RequestContext requestContext,
            ITokenCacheInternal cache)
        {
            AuthenticationRequestParameters requestParams = await base.CreateRequestParametersAsync(commonParameters, requestContext, cache).ConfigureAwait(false);

            return(requestParams);
        }
        internal override AuthenticationRequestParameters CreateRequestParameters(
            AcquireTokenCommonParameters commonParameters,
            RequestContext requestContext,
            ITokenCacheInternal cache)
        {
            AuthenticationRequestParameters requestParams = base.CreateRequestParameters(commonParameters, requestContext, cache);

            requestParams.ClientCredential = ServiceBundle.Config.ClientCredential;
            return(requestParams);
        }
        public static void UpdateAccessTokenUserAssertions(ITokenCacheInternal tokenCache, string assertion = "SomeAssertion")
        {
            var allAccessTokens = tokenCache.Accessor.GetAllAccessTokens();

            foreach (var atItem in allAccessTokens)
            {
                atItem.UserAssertionHash = assertion;
                tokenCache.AddAccessTokenCacheItem(atItem);
            }
        }
        public static void  UpdateRefreshTokenUserAssertions(ITokenCacheInternal tokenCache, string assertion = "SomeAssertion")
        {
            var rtItems = tokenCache.Accessor.GetAllRefreshTokens();

            foreach (var rtItem in rtItems)
            {
                rtItem.UserAssertionHash = assertion;
                tokenCache.AddRefreshTokenCacheItem(rtItem);
            }
        }
        internal MsalUserRefreshTokenControl(PublicClientApplication publicClient, MsalRefreshTokenCacheItem rtItem) : this()
        {
            _publicClient = publicClient;
            _cache        = publicClient.UserTokenCacheInternal;
            _rtItem       = rtItem;

            _accountItem  = _cache.GetAccountAsync(_rtItem, RequestContext.CreateForTest()).GetAwaiter().GetResult(); // todo: yuck
            upnLabel.Text = _accountItem.PreferredUsername;

            invalidateRefreshTokenBtn.Enabled = !_rtItem.Secret.Equals(GarbageRtValue, StringComparison.OrdinalIgnoreCase);
        }
        public static void UpdateAccessTokenUserAssertions(ITokenCacheInternal tokenCache, string assertion = "SomeAssertion")
        {
            var allAccessTokens = tokenCache.Accessor.GetAllAccessTokens();

            foreach (var atItem in allAccessTokens)
            {
                var newAt = atItem.WithUserAssertion(assertion);
                tokenCache.Accessor.SaveAccessToken(newAt);
                tokenCache.Accessor.DeleteAccessToken(atItem);
            }
        }
Exemple #21
0
 internal virtual AuthenticationRequestParameters CreateRequestParameters(
     AcquireTokenCommonParameters commonParameters,
     RequestContext requestContext,
     ITokenCacheInternal cache)
 {
     return(new AuthenticationRequestParameters(
                ServiceBundle,
                cache,
                commonParameters,
                requestContext));
 }
 public static void AddAccessTokenCacheItem(this ITokenCacheInternal tokenCache, MsalAccessTokenCacheItem accessTokenItem)
 {
     tokenCache.Semaphore.Wait();
     try
     {
         tokenCache.Accessor.SaveAccessToken(accessTokenItem);
     }
     finally
     {
         tokenCache.Semaphore.Release();
     }
 }
Exemple #23
0
        internal ClientApplicationBase(ApplicationConfiguration config)
        {
            ServiceBundle = Internal.ServiceBundle.Create(config);

            if (config.UserTokenLegacyCachePersistenceForTest != null)
            {
                UserTokenCacheInternal = new TokenCache(ServiceBundle, config.UserTokenLegacyCachePersistenceForTest, false);
            }
            else
            {
                UserTokenCacheInternal = new TokenCache(ServiceBundle, false);
            }
        }
Exemple #24
0
        internal ClientApplicationBase(ApplicationConfiguration config)
        {
            ServiceBundle = Internal.ServiceBundle.Create(config);
            ICacheSerializationProvider defaultCacheSerialization = ServiceBundle.PlatformProxy.CreateTokenCacheBlobStorage();

            if (config.UserTokenLegacyCachePersistenceForTest != null)
            {
                UserTokenCacheInternal = new TokenCache(ServiceBundle, config.UserTokenLegacyCachePersistenceForTest, false, defaultCacheSerialization);
            }
            else
            {
                UserTokenCacheInternal = config.UserTokenCacheInternalForTest ?? new TokenCache(ServiceBundle, false, defaultCacheSerialization);
            }
        }
 public static void DeleteAccessToken(
     this ITokenCacheInternal tokenCache,
     MsalAccessTokenCacheItem msalAccessTokenCacheItem)
 {
     tokenCache.Semaphore.Wait();
     try
     {
         tokenCache.Accessor.DeleteAccessToken(msalAccessTokenCacheItem.GetKey());
     }
     finally
     {
         tokenCache.Semaphore.Release();
     }
 }
Exemple #26
0
        public void GlobalSetup()
        {
            var serviceBundle = TestCommon.CreateServiceBundleWithCustomHttpManager(null, isLegacyCacheEnabled: EnableLegacyCache);

            _cache    = new TokenCache(serviceBundle, false);
            _response = TestConstants.CreateMsalTokenResponse(TestConstants.Utid);

            _requestParams         = TestCommon.CreateAuthenticationRequestParameters(serviceBundle);
            _requestParams.Account = new Account(TestConstants.s_userIdentifier, $"1{TestConstants.DisplayableId}", TestConstants.ProductionPrefNetworkEnvironment);

            AddHostToInstanceCache(serviceBundle, TestConstants.ProductionPrefCacheEnvironment);

            LegacyTokenCacheHelper.PopulateLegacyCache(serviceBundle.ApplicationLogger, _cache.LegacyPersistence, TokenCacheSize);
            TokenCacheHelper.AddRefreshTokensToCache(_cache.Accessor, TokenCacheSize);
        }
Exemple #27
0
        internal virtual async Task <AuthenticationRequestParameters> CreateRequestParametersAsync(
            AcquireTokenCommonParameters commonParameters,
            RequestContext requestContext,
            ITokenCacheInternal cache)
        {
            var authority = await Instance.Authority.CreateAuthorityForRequestAsync(
                requestContext,
                commonParameters.AuthorityOverride).ConfigureAwait(false);

            return(new AuthenticationRequestParameters(
                       ServiceBundle,
                       cache,
                       commonParameters,
                       requestContext,
                       authority));
        }
        internal virtual AuthenticationRequestParameters CreateRequestParameters(
            AcquireTokenCommonParameters commonParameters,
            RequestContext requestContext,
            ITokenCacheInternal cache)
        {
            var authority = Microsoft.Identity.Client.Instance.Authority.CreateAuthorityForRequest(
                requestContext.ServiceBundle.Config.AuthorityInfo,
                commonParameters.AuthorityOverride);

            return(new AuthenticationRequestParameters(
                       ServiceBundle,
                       cache,
                       commonParameters,
                       requestContext,
                       authority));
        }
        private async Task ValidateAccountAsync(ITokenCacheInternal cache)
        {
            // TODO: NEED TO LOOK INTO HOW TO HANDLE THIS TEST
            //ValidateCacheEntityValue
            //    (ExpectedAccountCacheValue, cache.GetAllAccountCacheItems(requestContext));

            var accountCacheItem = (await cache.GetAllAccountsAsync().ConfigureAwait(false)).First();
            var key = accountCacheItem.GetKey();

            Assert.AreEqual(_expectedAccountCacheKey, key.ToString());

            Assert.AreEqual(_expectedAccountCacheKeyIosService, key.iOSService);
            Assert.AreEqual(_expectedAccountCacheKeyIosAccount, key.iOSAccount);
            Assert.AreEqual(_expectedAccountCacheKeyIosGeneric, key.iOSGeneric);
            Assert.AreEqual(MsalCacheKeys.iOSAuthorityTypeToAttrType["MSSTS"], key.iOSType);
        }
        private async Task ValidateIdTokenAsync(ITokenCacheInternal cache)
        {
            // TODO: NEED TO LOOK INTO HOW TO HANDLE THIS TEST
            //ValidateCacheEntityValue
            //    (ExpectedIdTokenCacheValue, cache.GetAllIdTokenCacheItems(requestContext));

            var idTokenCacheItem = (await cache.GetAllIdTokensAsync(true).ConfigureAwait(false)).First();
            var key = idTokenCacheItem.GetKey();

            Assert.AreEqual(_expectedIdTokenCacheKey, key.ToString());

            Assert.AreEqual(_expectedIdTokenCacheKeyIosService, key.iOSService);
            Assert.AreEqual(_expectedIdTokenCacheKeyIosAccount, key.iOSAccount);
            Assert.AreEqual(_expectedIdTokenCacheKeyIosGeneric, key.iOSGeneric);
            Assert.AreEqual((int)MsalCacheKeys.iOSCredentialAttrType.IdToken, key.iOSType);
        }