Example #1
0
        private void CreateAdalCache(ICoreLogger logger, ILegacyCachePersistence legacyCachePersistence, string scopes)
        {
            var key = new AdalTokenCacheKey(
                MsalTestConstants.AuthorityHomeTenant,
                scopes,
                MsalTestConstants.ClientId,
                MsalTestConstants.TokenSubjectTypeUser,
                MsalTestConstants.UniqueId,
                MsalTestConstants.User.Username);

            var wrapper = new AdalResultWrapper()
            {
                Result = new AdalResult(null, null, DateTimeOffset.MinValue)
                {
                    UserInfo = new AdalUserInfo()
                    {
                        UniqueId      = MsalTestConstants.UniqueId,
                        DisplayableId = MsalTestConstants.User.Username
                    }
                },
                RefreshToken       = MsalTestConstants.ClientSecret,
                RawClientInfo      = MsalTestConstants.RawClientId,
                ResourceInResponse = scopes
            };

            IDictionary <AdalTokenCacheKey, AdalResultWrapper> dictionary =
                AdalCacheOperations.Deserialize(logger, legacyCachePersistence.LoadCache());

            dictionary[key] = wrapper;
            legacyCachePersistence.WriteCache(AdalCacheOperations.Serialize(logger, dictionary));
        }
        public async Task DoNotSaveRefreshTokenInAdalCacheForMsalB2CAuthorityTestAsync()
        {
            var appConfig = new ApplicationConfiguration()
            {
                ClientId      = TestConstants.ClientId,
                RedirectUri   = TestConstants.RedirectUri,
                AuthorityInfo = AuthorityInfo.FromAuthorityUri(TestConstants.B2CAuthority, false)
            };

            var serviceBundle         = ServiceBundle.Create(appConfig);
            ITokenCacheInternal cache = new TokenCache(serviceBundle);

            MsalTokenResponse response = TestConstants.CreateMsalTokenResponse();

            var requestParams = CreateAuthenticationRequestParameters(serviceBundle, authority: Authority.CreateAuthority(serviceBundle, TestConstants.B2CAuthority));

            requestParams.TenantUpdatedCanonicalAuthority = TestConstants.AuthorityTestTenant;

            AddHostToInstanceCache(serviceBundle, TestConstants.ProductionPrefNetworkEnvironment);

            await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);

            Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count());

            IDictionary <AdalTokenCacheKey, AdalResultWrapper> dictionary =
                AdalCacheOperations.Deserialize(serviceBundle.DefaultLogger, cache.LegacyPersistence.LoadCache());

            cache.LegacyPersistence.WriteCache(AdalCacheOperations.Serialize(serviceBundle.DefaultLogger, dictionary));

            // ADAL cache is empty because B2C scenario is only for MSAL
            Assert.AreEqual(0, dictionary.Count);
        }
        void ITokenCacheInternal.ClearAdalCache()
        {
            IDictionary <AdalTokenCacheKey, AdalResultWrapper> dictionary = AdalCacheOperations.Deserialize(Logger, LegacyCachePersistence.LoadCache());

            dictionary.Clear();
            LegacyCachePersistence.WriteCache(AdalCacheOperations.Serialize(Logger, dictionary));
        }
        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);
            }
        }
        private void AssertCacheEntryCount(int expectedEntryCount)
        {
            IDictionary <AdalTokenCacheKey, AdalResultWrapper> cache =
                AdalCacheOperations.Deserialize(_legacyCachePersistence.LoadCache());

            Assert.AreEqual(expectedEntryCount, cache.Count);
        }
        public void RemoveAdalUser_RemovesUserNoClientInfo_And_NoDisplayName()
        {
            // Arrange
            PopulateLegacyCache(_legacyCachePersistence);
            IDictionary <AdalTokenCacheKey, AdalResultWrapper> adalCacheBeforeDelete =
                AdalCacheOperations.Deserialize(_legacyCachePersistence.LoadCache());

            Assert.AreEqual(6, adalCacheBeforeDelete.Count);

            // Act - nothing happens and a message is logged
            CacheFallbackOperations.RemoveAdalUser(
                _legacyCachePersistence,
                CoreTestConstants.ClientId,
                "",
                "");

            // Assert
            AssertCacheEntryCount(6);

            MsalLogger.Default.Received().Error(Arg.Is <string>(CoreErrorMessages.InternalErrorCacheEmptyUsername));
        }
Example #7
0
        private void ValidateCacheEntitiesEnvironment(TokenCache cache, string expectedEnvironment)
        {
            var requestContext = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null));
            ICollection <MsalAccessTokenCacheItem> accessTokens = cache.GetAllAccessTokensForClient(requestContext);

            foreach (var at in accessTokens)
            {
                Assert.AreEqual(expectedEnvironment, at.Environment);
            }

            ICollection <MsalRefreshTokenCacheItem> refreshTokens = cache.GetAllRefreshTokensForClient(requestContext);

            foreach (var rt in refreshTokens)
            {
                Assert.AreEqual(expectedEnvironment, rt.Environment);
            }

            ICollection <MsalIdTokenCacheItem> idTokens = cache.GetAllIdTokensForClient(requestContext);

            foreach (var id in idTokens)
            {
                Assert.AreEqual(expectedEnvironment, id.Environment);
            }

            ICollection <MsalAccountCacheItem> accounts = cache.GetAllAccounts(requestContext);

            foreach (var account in accounts)
            {
                Assert.AreEqual(expectedEnvironment, account.Environment);
            }

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

            foreach (KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> kvp in adalCache)
            {
                Assert.AreEqual(expectedEnvironment, new Uri(kvp.Key.Authority).Host);
            }
        }
        private async Task ValidateCacheEntitiesEnvironmentAsync(ITokenCacheInternal cache, string expectedEnvironment)
        {
            var requestContext = RequestContext.CreateForTest();
            var accessTokens   = await cache.GetAllAccessTokensAsync(true).ConfigureAwait(false);

            foreach (var at in accessTokens)
            {
                Assert.AreEqual(expectedEnvironment, at.Environment);
            }

            var refreshTokens = await cache.GetAllRefreshTokensAsync(true).ConfigureAwait(false);

            foreach (var rt in refreshTokens)
            {
                Assert.AreEqual(expectedEnvironment, rt.Environment);
            }

            var idTokens = await cache.GetAllIdTokensAsync(true).ConfigureAwait(false);

            foreach (var id in idTokens)
            {
                Assert.AreEqual(expectedEnvironment, id.Environment);
            }

            var accounts = await cache.GetAllAccountsAsync().ConfigureAwait(false);

            foreach (var account in accounts)
            {
                Assert.AreEqual(expectedEnvironment, account.Environment);
            }

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

            foreach (KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> kvp in adalCache)
            {
                Assert.AreEqual(expectedEnvironment, new Uri(kvp.Key.Authority).Host);
            }
        }
Example #9
0
        public void UnifiedCache_MsalStoresToAndReadRtFromAdalCache()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                var app = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId)
                          .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                          .WithHttpManager(httpManager)
                          .WithTelemetry(new TraceTelemetryConfig())
                          .WithUserTokenLegacyCachePersistenceForTest(
                    new TestLegacyCachePersistance())
                          .BuildConcrete();

                MsalMockHelpers.ConfigureMockWebUI(
                    app.ServiceBundle.PlatformProxy,
                    AuthorizationResult.FromUri(app.AppConfig.RedirectUri + "?code=some-code"));
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityCommonTenant);
                httpManager.AddSuccessTokenResponseMockHandlerForPost(ClientApplicationBase.DefaultAuthority);

                AuthenticationResult result = app.AcquireTokenInteractive(MsalTestConstants.Scope).ExecuteAsync(CancellationToken.None).Result;
                Assert.IsNotNull(result);

                // make sure Msal stored RT in Adal cache
                IDictionary <AdalTokenCacheKey, AdalResultWrapper> adalCacheDictionary =
                    AdalCacheOperations.Deserialize(app.ServiceBundle.DefaultLogger, app.UserTokenCacheInternal.LegacyPersistence.LoadCache());

                Assert.IsTrue(adalCacheDictionary.Count == 1);

                var requestContext = new RequestContext(app.ServiceBundle, Guid.NewGuid());
                var accounts       = app.UserTokenCacheInternal.GetAccountsAsync(
                    MsalTestConstants.AuthorityCommonTenant, requestContext).Result;
                foreach (IAccount account in accounts)
                {
                    app.UserTokenCacheInternal.RemoveMsalAccountWithNoLocks(account, requestContext);
                }

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler()
                {
                    ExpectedMethod   = HttpMethod.Post,
                    ExpectedPostData = new Dictionary <string, string>()
                    {
                        { "grant_type", "refresh_token" }
                    },
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(
                        MsalTestConstants.UniqueId,
                        MsalTestConstants.DisplayableId,
                        MsalTestConstants.Scope.ToArray())
                });

                // Using RT from Adal cache for silent call
                AuthenticationResult result1 = app
                                               .AcquireTokenSilent(MsalTestConstants.Scope, result.Account)
                                               .WithAuthority(MsalTestConstants.AuthorityCommonTenant)
                                               .WithForceRefresh(false)
                                               .ExecuteAsync(CancellationToken.None)
                                               .Result;

                Assert.IsNotNull(result1);
            }
        }
        public void UnifiedCache_MsalStoresToAndReadRtFromAdalCache()
        {
            using (var mocks = new MockHttpAndServiceBundle())
            {
                var httpManager = mocks.HttpManager;
                httpManager.AddInstanceDiscoveryMockHandler();

                var app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                          .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                          .WithHttpManager(httpManager)
                          .WithTelemetry(new TraceTelemetryConfig())
                          .WithUserTokenLegacyCachePersistenceForTest(
                    new TestLegacyCachePersistance())
                          .BuildConcrete();


                app.ServiceBundle.ConfigureMockWebUI(
                    AuthorizationResult.FromUri(app.AppConfig.RedirectUri + "?code=some-code"));

                HttpResponseMessage response = MockHelpers.CreateSuccessTokenResponseMessageWithUid(
                    TestConstants.Uid,
                    TestConstants.Utid,
                    "*****@*****.**");

                httpManager.AddResponseMockHandlerForPost(response);

                AuthenticationResult result = app.AcquireTokenInteractive(TestConstants.s_scope).ExecuteAsync(CancellationToken.None).Result;
                Assert.IsNotNull(result);

                // make sure Msal stored RT in Adal cache
                IDictionary <AdalTokenCacheKey, AdalResultWrapper> adalCacheDictionary =
                    AdalCacheOperations.Deserialize(app.ServiceBundle.ApplicationLogger, app.UserTokenCacheInternal.LegacyPersistence.LoadCache());

                Assert.IsTrue(adalCacheDictionary.Count == 1);

                var requestContext = new RequestContext(app.ServiceBundle, Guid.NewGuid());

                var authority = Microsoft.Identity.Client.Instance.Authority.CreateAuthorityForRequestAsync(
                    requestContext, null).Result;

                AuthenticationRequestParameters reqParams = new AuthenticationRequestParameters(
                    mocks.ServiceBundle,
                    app.UserTokenCacheInternal,
                    new Client.ApiConfig.Parameters.AcquireTokenCommonParameters(),
                    requestContext,
                    authority);

                var accounts = app.UserTokenCacheInternal.GetAccountsAsync(reqParams).Result;
                foreach (IAccount account in accounts)
                {
                    app.UserTokenCacheInternal.RemoveMsalAccountWithNoLocks(account, requestContext);
                }

                Assert.AreEqual(0, httpManager.QueueSize);

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler()
                {
                    ExpectedMethod   = HttpMethod.Post,
                    ExpectedPostData = new Dictionary <string, string>()
                    {
                        { "grant_type", "refresh_token" }
                    },
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(
                        TestConstants.UniqueId,
                        TestConstants.DisplayableId,
                        TestConstants.s_scope.ToArray())
                });

                // Using RT from Adal cache for silent call
                AuthenticationResult result1 = app
                                               .AcquireTokenSilent(TestConstants.s_scope, result.Account)
                                               .WithAuthority(TestConstants.AuthorityCommonTenant)
                                               .WithForceRefresh(false)
                                               .ExecuteAsync(CancellationToken.None)
                                               .Result;

                Assert.IsNotNull(result1);
            }
        }
Example #11
0
        public void UnifiedCache_MsalStoresToAndReadRtFromAdalCache()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                httpManager.AddInstanceDiscoveryMockHandler();

                PublicClientApplication app = new PublicClientApplication(
                    serviceBundle,
                    MsalTestConstants.ClientId,
                    ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache =
                    {
                        LegacyCachePersistence = new TestLegacyCachePersistance()
                    }
                };

                MsalMockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                           app.RedirectUri + "?code=some-code"));
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityHomeTenant);
                httpManager.AddSuccessTokenResponseMockHandlerForPost();

                AuthenticationResult result = app.AcquireTokenAsync(MsalTestConstants.Scope).Result;
                Assert.IsNotNull(result);

                // make sure Msal stored RT in Adal cache
                IDictionary <AdalTokenCacheKey, AdalResultWrapper> adalCacheDictionary =
                    AdalCacheOperations.Deserialize(app.UserTokenCache.LegacyCachePersistence.LoadCache());

                Assert.IsTrue(adalCacheDictionary.Count == 1);

                var requestContext = new RequestContext(null, new MsalLogger(Guid.Empty, null));
                var accounts       =
                    app.UserTokenCache.GetAccounts(MsalTestConstants.AuthorityCommonTenant, false, requestContext);
                foreach (IAccount account in accounts)
                {
                    app.UserTokenCache.RemoveMsalAccount(account, requestContext);
                }

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler()
                {
                    Method   = HttpMethod.Post,
                    PostData = new Dictionary <string, string>()
                    {
                        { "grant_type", "refresh_token" }
                    },
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(
                        MsalTestConstants.UniqueId,
                        MsalTestConstants.DisplayableId,
                        MsalTestConstants.Scope.ToArray())
                });

                // Using RT from Adal cache for silent call
                AuthenticationResult result1 = app.AcquireTokenSilentAsync(
                    MsalTestConstants.Scope,
                    result.Account,
                    MsalTestConstants.AuthorityCommonTenant,
                    false).Result;

                Assert.IsNotNull(result1);
            }
        }