public void GetExpiredAccessToken_WithExtendedExpireStillValid_Test()
        {
            using (var harness = CreateTestHarness(isExtendedTokenLifetimeEnabled: true))
            {
                ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle);

                var atItem = new MsalAccessTokenCacheItem(
                    TestConstants.ProductionPrefNetworkEnvironment,
                    TestConstants.ClientId,
                    TestConstants.s_scope.AsSingleString(),
                    TestConstants.Utid,
                    null,
                    new DateTimeOffset(DateTime.UtcNow),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)),
                    MockHelpers.CreateClientInfo());

                atItem.Secret = atItem.GetKey().ToString();
                cache.Accessor.SaveAccessToken(atItem);

                var param = harness.CreateAuthenticationRequestParameters(
                    TestConstants.AuthorityTestTenant,
                    new SortedSet <string>(),
                    cache,
                    account: new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null));

                var cacheItem = cache.FindAccessTokenAsync(param).Result;

                Assert.IsNotNull(cacheItem);
                Assert.AreEqual(atItem.GetKey().ToString(), cacheItem.GetKey().ToString());
                Assert.IsTrue(cacheItem.IsExtendedLifeTimeToken);
            }
        }
        public void GetAppTokenFromCacheTest()
        {
            using (var harness = CreateTestHarness())
            {
                ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle);

                var atItem = new MsalAccessTokenCacheItem(
                    TestConstants.ProductionPrefNetworkEnvironment,
                    TestConstants.ClientId,
                    TestConstants.s_scope.AsSingleString(),
                    TestConstants.Utid,
                    null,
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn)),
                    MockHelpers.CreateClientInfo());

                string atKey = atItem.GetKey().ToString();
                atItem.Secret = atKey;

                cache.Accessor.SaveAccessToken(atItem);

                var authParams = harness.CreateAuthenticationRequestParameters(
                    TestConstants.AuthorityTestTenant,
                    TestConstants.s_scope,
                    cache);
                authParams.ClientCredential          = TestConstants.s_credentialWithSecret;
                authParams.IsClientCredentialRequest = true;

                var cacheItem = cache.FindAccessTokenAsync(authParams).Result;

                Assert.IsNotNull(cacheItem);
                Assert.AreEqual(atItem.GetKey().ToString(), cacheItem.GetKey().ToString());
            }
        }
Exemple #3
0
        public void SaveAccessToken(MsalAccessTokenCacheItem item)
        {
            string key = item.GetKey().ToString();

            // if a conflict occurs, pick the latest value
            _accessTokenCacheDictionary[key] = item;
        }
Exemple #4
0
        public void SaveAccessToken(MsalAccessTokenCacheItem item)
        {
            ISharedPreferencesEditor editor = _accessTokenSharedPreference.Edit();

            editor.PutString(item.GetKey().ToString(), item.ToJsonString());
            editor.Apply();
        }
        public void GetAccessTokenExpiryInRangeTest()
        {
            using (var harness = CreateTestHarness())
            {
                ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle);

                var atItem = new MsalAccessTokenCacheItem(
                    TestConstants.ProductionPrefNetworkEnvironment,
                    TestConstants.ClientId,
                    TestConstants.s_scope.AsSingleString(),
                    TestConstants.Utid,
                    "",
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromMinutes(4)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)),
                    MockHelpers.CreateClientInfo());

                atItem.Secret = atItem.GetKey().ToString();
                cache.Accessor.SaveAccessToken(atItem);

                var param = harness.CreateAuthenticationRequestParameters(
                    TestConstants.AuthorityTestTenant,
                    new SortedSet <string>(),
                    cache,
                    account: new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null));

                Assert.IsNull(cache.FindAccessTokenAsync(param).Result);
            }
        }
Exemple #6
0
        public void GetExactScopesMatchedAccessTokenTest()
        {
            using (var harness = new MockHttpAndServiceBundle())
            {
                harness.HttpManager.AddInstanceDiscoveryMockHandler();
                ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle);
                var atItem = new MsalAccessTokenCacheItem(
                    MsalTestConstants.ProductionPrefNetworkEnvironment,
                    MsalTestConstants.ClientId,
                    MsalTestConstants.Scope.AsSingleString(),
                    MsalTestConstants.Utid,
                    "",
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn)),
                    MockHelpers.CreateClientInfo());

                // create key out of access token cache item and then
                // set it as the value of the access token.
                string atKey = atItem.GetKey().ToString();
                atItem.Secret = atKey;

                cache.Accessor.SaveAccessToken(atItem);
                var item = cache.FindAccessTokenAsync(
                    harness.CreateAuthenticationRequestParameters(MsalTestConstants.AuthorityTestTenant, MsalTestConstants.Scope, account: MsalTestConstants.User)).Result;

                Assert.IsNotNull(item);
                Assert.AreEqual(atKey, item.Secret);
            }
        }
Exemple #7
0
        public void GetExpiredAccessTokenTest()
        {
            using (var harness = new MockHttpAndServiceBundle())
            {
                harness.HttpManager.AddInstanceDiscoveryMockHandler();
                ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle);

                var atItem = new MsalAccessTokenCacheItem(
                    MsalTestConstants.ProductionPrefNetworkEnvironment,
                    MsalTestConstants.ClientId,
                    MsalTestConstants.Scope.AsSingleString(),
                    MsalTestConstants.Utid,
                    null,
                    new DateTimeOffset(DateTime.UtcNow),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)),
                    MockHelpers.CreateClientInfo());

                atItem.Secret = atItem.GetKey().ToString();
                cache.Accessor.SaveAccessToken(atItem);

                var param = harness.CreateAuthenticationRequestParameters(
                    MsalTestConstants.AuthorityTestTenant,
                    new SortedSet <string>(),
                    account: new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null));

                Assert.IsNull(cache.FindAccessTokenAsync(param).Result);
            }
        }
        public void GetSubsetScopesMatchedAccessTokenTest()
        {
            using (var harness = CreateTestHarness())
            {
                ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle);

                var atItem = new MsalAccessTokenCacheItem(
                    TestConstants.ProductionPrefNetworkEnvironment,
                    TestConstants.ClientId,
                    TestConstants.s_scope.AsSingleString(),
                    TestConstants.Utid,
                    null,
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(1)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)),
                    MockHelpers.CreateClientInfo());

                // create key out of access token cache item and then
                // set it as the value of the access token.
                string atKey = atItem.GetKey().ToString();
                atItem.Secret = atKey;

                cache.Accessor.SaveAccessToken(atItem);
                var param = harness.CreateAuthenticationRequestParameters(
                    TestConstants.AuthorityTestTenant,
                    new SortedSet <string>(),
                    cache,
                    account: TestConstants.s_user);

                param.Scope.Add("r1/scope1");
                var item = cache.FindAccessTokenAsync(param).Result;

                Assert.IsNotNull(item);
                Assert.AreEqual(atKey, item.Secret);
            }
        }
        public void SaveAccessToken(MsalAccessTokenCacheItem item)
        {
            string key = item.GetKey().ToString();

            // if a conflict occurs, pick the latest value
            _accessTokenCacheDictionary.AddOrUpdate(key, item, (k, oldValue) => item);
        }
Exemple #10
0
        public void SaveAccessToken(MsalAccessTokenCacheItem item)
        {
            string itemKey      = item.GetKey().ToString();
            string partitionKey = CacheKeyFactory.GetKeyFromCachedItem(item);

            AccessTokenCacheDictionary
            .GetOrAdd(partitionKey, new ConcurrentDictionary <string, MsalAccessTokenCacheItem>())[itemKey] = item;    // if a conflict occurs, pick the latest value
        }
Exemple #11
0
        public void SaveAccessToken(MsalAccessTokenCacheItem item)
        {
            ApplicationDataCompositeValue composite = new ApplicationDataCompositeValue();

            SetCacheValue(composite, JsonHelper.SerializeToJson(item));
            var key = item.GetKey().GetUWPFixedSizeKey();

            _accessTokenContainer.Values[/*CoreCryptographyHelpers.CreateBase64UrlEncodedSha256Hash(cacheKey)*/ key] = composite;
        }
        public void SaveAccessToken(MsalAccessTokenCacheItem item)
        {
            string itemKey      = item.GetKey().ToString();
            string partitionKey = CacheKeyFactory.GetClientCredentialKey(item.ClientId, item.TenantId, item.KeyId);

            // if a conflict occurs, pick the latest value
            AccessTokenCacheDictionary
            .GetOrAdd(partitionKey, new ConcurrentDictionary <string, MsalAccessTokenCacheItem>())[itemKey] = item;
        }
        public void DeleteAccessToken(MsalAccessTokenCacheItem item)
        {
            var partitionKey = CacheKeyFactory.GetClientCredentialKey(item.ClientId, item.TenantId, item.KeyId);

            AccessTokenCacheDictionary.TryGetValue(partitionKey, out var partition);
            if (partition == null || !partition.TryRemove(item.GetKey().ToString(), out _))
            {
                _logger.InfoPii(
                    $"Cannot delete access token because it was not found in the cache. Key {item.GetKey()}.",
                    "Cannot delete access token because it was not found in the cache.");
            }
        }
        public void SaveAccessToken(MsalAccessTokenCacheItem item)
        {
            var key = item.GetKey();

            var account = key.GetiOSAccountKey();
            var service = key.GetiOSServiceKey();
            var generic = key.GetiOSGenericKey();
            var type    = (int)CredentialAttrType.AccessToken;

            var value = JsonHelper.SerializeToJson(item);

            Save(account, service, generic, type, value);
        }
 public static void DeleteAccessToken(
     this ITokenCacheInternal tokenCache,
     MsalAccessTokenCacheItem msalAccessTokenCacheItem)
 {
     tokenCache.Semaphore.Wait();
     try
     {
         tokenCache.Accessor.DeleteAccessToken(msalAccessTokenCacheItem.GetKey());
     }
     finally
     {
         tokenCache.Semaphore.Release();
     }
 }
Exemple #16
0
        public MsalIdTokenCacheItem GetIdToken(MsalAccessTokenCacheItem accessTokenCacheItem)
        {
            string partitionKey = CacheKeyFactory.GetIdTokenKeyFromCachedItem(accessTokenCacheItem);

            IdTokenCacheDictionary.TryGetValue(partitionKey, out var partition);
            if (partition != null && partition.TryGetValue(accessTokenCacheItem.GetIdTokenItemKey().ToString(), out var idToken))
            {
                return(idToken);
            }

            _logger.WarningPii(
                $"Could not find an id token for the access token with key {accessTokenCacheItem.GetKey()}",
                $"Could not find an id token for the access token for realm {accessTokenCacheItem.TenantId} ");
            return(null);
        }
        private void RefreshCacheView()
        {
            var tokenCache = App.MsalPublicClient.UserTokenCache;

            var requestContext = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null));

            IDictionary <string, MsalAccessTokenCacheItem> accessTokens = new Dictionary <string, MsalAccessTokenCacheItem>();

            foreach (var accessItemStr in tokenCache.GetAllAccessTokenCacheItems(requestContext))
            {
                MsalAccessTokenCacheItem accessItem = JsonHelper.DeserializeFromJson <MsalAccessTokenCacheItem>(accessItemStr);
                accessTokens.Add(accessItem.GetKey().ToString(), accessItem);
            }
            accessTokenCacheItems.ItemsSource = accessTokens;

            IDictionary <string, MsalRefreshTokenCacheItem> refreshTokens = new Dictionary <string, MsalRefreshTokenCacheItem>();

            foreach (var refreshItemStr in tokenCache.GetAllRefreshTokenCacheItems(requestContext))
            {
                MsalRefreshTokenCacheItem refreshItem = JsonHelper.DeserializeFromJson <MsalRefreshTokenCacheItem>(refreshItemStr);
                refreshTokens.Add(refreshItem.GetKey().ToString(), refreshItem);
            }
            refreshTokenCacheItems.ItemsSource = refreshTokens;

            IDictionary <string, MsalIdTokenCacheItem> idTokens = new Dictionary <string, MsalIdTokenCacheItem>();

            foreach (var idItemStr in tokenCache.GetAllIdTokenCacheItems(requestContext))
            {
                MsalIdTokenCacheItem idItem = JsonHelper.DeserializeFromJson <MsalIdTokenCacheItem>(idItemStr);
                idTokens.Add(idItem.GetKey().ToString(), idItem);
            }
            idTokenCacheItems.ItemsSource = idTokens;

            IDictionary <string, MsalAccountCacheItem> accounts = new Dictionary <string, MsalAccountCacheItem>();

            foreach (var accountStr in tokenCache.GetAllAccountCacheItems(requestContext))
            {
                MsalAccountCacheItem accountItem = JsonHelper.DeserializeFromJson <MsalAccountCacheItem>(accountStr);
                accounts.Add(accountItem.GetKey().ToString(), accountItem);
            }
            accountsCacheItems.ItemsSource = accounts;
        }
        private void AssertAccessTokenCacheItemsAreEqual(MsalAccessTokenCacheItem expected, MsalAccessTokenCacheItem actual)
        {
            AssertCredentialCacheItemBaseItemsAreEqual(expected, actual);

            Assert.AreEqual(expected.Authority, actual.Authority, nameof(actual.Authority));
            Assert.AreEqual(expected.ExpiresOnUnixTimestamp, actual.ExpiresOnUnixTimestamp, nameof(actual.ExpiresOnUnixTimestamp));
            Assert.AreEqual(expected.ExtendedExpiresOnUnixTimestamp, actual.ExtendedExpiresOnUnixTimestamp, nameof(actual.ExtendedExpiresOnUnixTimestamp));
            Assert.AreEqual(expected.CachedAt, actual.CachedAt, nameof(actual.CachedAt));
            Assert.AreEqual(expected.ExpiresOn, actual.ExpiresOn, nameof(actual.ExpiresOn));
            Assert.AreEqual(expected.ExtendedExpiresOn, actual.ExtendedExpiresOn, nameof(actual.ExtendedExpiresOn));
            Assert.AreEqual(expected.IsExtendedLifeTimeToken, actual.IsExtendedLifeTimeToken, nameof(actual.IsExtendedLifeTimeToken));
            Assert.AreEqual(expected.GetKey().ToString(), actual.GetKey().ToString());
            CollectionAssert.AreEqual(expected.ScopeSet.ToList(), actual.ScopeSet.ToList(), nameof(actual.ScopeSet));
            Assert.AreEqual(expected.TenantId, actual.TenantId, nameof(actual.TenantId));
            Assert.AreEqual(expected.UserAssertionHash, actual.UserAssertionHash, nameof(actual.UserAssertionHash));
            Assert.AreEqual(expected.RefreshOnUnixTimestamp, actual.RefreshOnUnixTimestamp, nameof(actual.RefreshOnUnixTimestamp));
            Assert.AreEqual(expected.RefreshOn, actual.RefreshOn, nameof(actual.RefreshOn));
            Assert.AreEqual(expected.KeyId, actual.KeyId, nameof(actual.KeyId));
            Assert.AreEqual(expected.TokenType, actual.TokenType, nameof(actual.TokenType));
        }
Exemple #19
0
        public void GetAccessTokenNoUserAssertionInCacheTest()
        {
            using (var harness = new MockHttpAndServiceBundle())
            {
                harness.HttpManager.AddInstanceDiscoveryMockHandler();
                ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle);

                var atItem = new MsalAccessTokenCacheItem(
                    MsalTestConstants.ProductionPrefNetworkEnvironment,
                    MsalTestConstants.ClientId,
                    MsalTestConstants.Scope.AsSingleString(),
                    MsalTestConstants.Utid,
                    null,
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(1)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)),
                    MockHelpers.CreateClientInfo());

                // create key out of access token cache item and then
                // set it as the value of the access token.
                string atKey = atItem.GetKey().ToString();
                atItem.Secret = atKey;

                cache.Accessor.SaveAccessToken(atItem);

                var authParams = harness.CreateAuthenticationRequestParameters(
                    MsalTestConstants.AuthorityTestTenant,
                    MsalTestConstants.Scope);
                authParams.UserAssertion = new UserAssertion(
                    harness.ServiceBundle.PlatformProxy.CryptographyManager.CreateBase64UrlEncodedSha256Hash(atKey));

                var item = cache.FindAccessTokenAsync(authParams).Result;

                // cache lookup should fail because there was no userassertion hash in the matched
                // token cache item.

                Assert.IsNull(item);
            }
        }
        public void GetAccessTokenUserAssertionMismatchInCacheTest()
        {
            using (var harness = CreateTestHarness())
            {
                ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle);

                var atItem = new MsalAccessTokenCacheItem(
                    TestConstants.ProductionPrefNetworkEnvironment,
                    TestConstants.ClientId,
                    TestConstants.s_scope.AsSingleString(),
                    TestConstants.Utid,
                    null,
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(1)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)),
                    MockHelpers.CreateClientInfo());

                // create key out of access token cache item and then
                // set it as the value of the access token.
                string atKey = atItem.GetKey().ToString();
                atItem.Secret = atKey;

                atItem.UserAssertionHash = harness.ServiceBundle.PlatformProxy.CryptographyManager.CreateBase64UrlEncodedSha256Hash(atKey);

                cache.Accessor.SaveAccessToken(atItem);

                var authParams = harness.CreateAuthenticationRequestParameters(
                    TestConstants.AuthorityTestTenant,
                    TestConstants.s_scope,
                    cache);
                authParams.UserAssertion = new UserAssertion(atItem.UserAssertionHash + "-random");

                var item = cache.FindAccessTokenAsync(authParams).Result;

                // cache lookup should fail because there was userassertion hash did not match the one
                // stored in token cache item.
                Assert.IsNull(item);
            }
        }
Exemple #21
0
        public void GetIntersectedScopesMatchedAccessTokenTest()
        {
            using (var harness = new MockHttpAndServiceBundle())
            {
                harness.HttpManager.AddInstanceDiscoveryMockHandler();
                ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle);

                var atItem = new MsalAccessTokenCacheItem(
                    MsalTestConstants.ProductionPrefNetworkEnvironment,
                    MsalTestConstants.ClientId,
                    MsalTestConstants.Scope.AsSingleString(),
                    MsalTestConstants.Utid,
                    null,
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(1)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)),
                    MockHelpers.CreateClientInfo());

                // create key out of access token cache item and then
                // set it as the value of the access token.
                string atKey = atItem.GetKey().ToString();
                atItem.Secret = atKey;

                cache.Accessor.SaveAccessToken(atItem);

                var param = harness.CreateAuthenticationRequestParameters(
                    MsalTestConstants.AuthorityHomeTenant,
                    new SortedSet <string>(),
                    account: new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null));

                param.Scope.Add(MsalTestConstants.Scope.First());
                param.Scope.Add("non-existent-scopes");
                var item = cache.FindAccessTokenAsync(param).Result;

                // intersected scopes are not returned.
                Assert.IsNull(item);
            }
        }
        public void GetAccessTokenMatchedUserAssertionInCacheTest()
        {
            using (var harness = CreateTestHarness())
            {
                ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle);

                var atItem = new MsalAccessTokenCacheItem(
                    TestConstants.ProductionPrefNetworkEnvironment,
                    TestConstants.ClientId,
                    TestConstants.s_scope.AsSingleString(),
                    TestConstants.Utid,
                    null,
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(1)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)),
                    MockHelpers.CreateClientInfo());

                // create key out of access token cache item and then
                // set it as the value of the access token.
                string atKey = atItem.GetKey().ToString();
                atItem.Secret            = atKey;
                atItem.UserAssertionHash = harness.ServiceBundle.PlatformProxy.CryptographyManager.CreateBase64UrlEncodedSha256Hash(atKey);

                cache.Accessor.SaveAccessToken(atItem);

                var authParams = harness.CreateAuthenticationRequestParameters(
                    TestConstants.AuthorityTestTenant,
                    TestConstants.s_scope,
                    cache);
                authParams.UserAssertion = new UserAssertion(atKey);

                ((TokenCache)cache).AfterAccess = AfterAccessNoChangeNotification;
                var item = cache.FindAccessTokenAsync(authParams).Result;

                Assert.IsNotNull(item);
                Assert.AreEqual(atKey, item.Secret);
            }
        }
 private void deleteAccessTokenButton_Click(object sender, EventArgs e)
 {
     _cache.Accessor.DeleteAccessToken(_item.GetKey());
     RefreshViewAsyncDelegate?.Invoke();
 }
 public void DeleteAccessToken(MsalAccessTokenCacheItem item)
 {
     Remove(item.GetKey());
 }
Exemple #25
0
 public void SaveAccessToken(MsalAccessTokenCacheItem item)
 {
     _accessTokenCacheDictionary[item.GetKey().ToString()] = item;
 }
Exemple #26
0
 public void DeleteAccessToken(MsalAccessTokenCacheItem item)
 {
     Delete(item.GetKey().ToString(), _accessTokenSharedPreference.Edit());
 }
        public void NoCacheLookup()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager, _myReceiver);

                var authority = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityHomeTenant, false);
                var cache     = new TokenCache()
                {
                    ClientId      = MsalTestConstants.ClientId,
                    ServiceBundle = serviceBundle
                };

                var atItem = new MsalAccessTokenCacheItem(
                    MsalTestConstants.ProductionPrefNetworkEnvironment,
                    MsalTestConstants.ClientId,
                    "Bearer",
                    MsalTestConstants.Scope.AsSingleString(),
                    MsalTestConstants.Utid,
                    null,
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(7200)),
                    MockHelpers.CreateClientInfo());

                string atKey = atItem.GetKey().ToString();
                atItem.Secret = atKey;
                cache.TokenCacheAccessor.SaveAccessToken(atItem);

                var ui = new MockWebUI()
                {
                    MockResult = new AuthorizationResult(
                        AuthorizationStatus.Success,
                        MsalTestConstants.AuthorityHomeTenant + "?code=some-code")
                };

                MockInstanceDiscoveryAndOpenIdRequest(httpManager);

                httpManager.AddSuccessTokenResponseMockHandlerForPost();

                var parameters = new AuthenticationRequestParameters
                {
                    Authority            = authority,
                    ClientId             = MsalTestConstants.ClientId,
                    Scope                = MsalTestConstants.Scope,
                    TokenCache           = cache,
                    RequestContext       = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null)),
                    RedirectUri          = new Uri("some://uri"),
                    ExtraQueryParameters = "extra=qp"
                };

                var request = new InteractiveRequest(
                    serviceBundle,
                    parameters,
                    ApiEvent.ApiIds.None,
                    MsalTestConstants.ScopeForAnotherResource.ToArray(),
                    MsalTestConstants.DisplayableId,
                    UIBehavior.SelectAccount,
                    ui);
                Task <AuthenticationResult> task = request.RunAsync(CancellationToken.None);
                task.Wait();
                var result = task.Result;
                Assert.IsNotNull(result);
                Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCount);
                Assert.AreEqual(2, cache.TokenCacheAccessor.AccessTokenCount);
                Assert.AreEqual(result.AccessToken, "some-access-token");

                Assert.IsNotNull(
                    _myReceiver.EventsReceived.Find(
                        anEvent => // Expect finding such an event
                        anEvent[EventBase.EventNameKey].EndsWith("ui_event") &&
                        anEvent[UiEvent.UserCancelledKey] == "false"));
                Assert.IsNotNull(
                    _myReceiver.EventsReceived.Find(
                        anEvent => // Expect finding such an event
                        anEvent[EventBase.EventNameKey].EndsWith("api_event") &&
                        anEvent[ApiEvent.UiBehaviorKey] == "select_account"));
                Assert.IsNotNull(
                    _myReceiver.EventsReceived.Find(
                        anEvent => // Expect finding such an event
                        anEvent[EventBase.EventNameKey].EndsWith("ui_event") &&
                        anEvent[UiEvent.AccessDeniedKey] == "false"));
            }
        }
Exemple #28
0
        public void TestGetAccounts()
        {
            var tokenCacheHelper = new TokenCacheHelper();

            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId)
                                              .WithHttpManager(httpManager)
                                              .BuildConcrete();

                IEnumerable <IAccount> accounts = app.GetAccountsAsync().Result;
                Assert.IsNotNull(accounts);
                Assert.IsFalse(accounts.Any());
                tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);
                accounts = app.GetAccountsAsync().Result;
                Assert.IsNotNull(accounts);
                Assert.AreEqual(1, accounts.Count());

                var atItem = new MsalAccessTokenCacheItem(
                    MsalTestConstants.ProductionPrefCacheEnvironment,
                    MsalTestConstants.ClientId,
                    MsalTestConstants.Scope.AsSingleString(),
                    MsalTestConstants.Utid,
                    null,
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3600)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(7200)),
                    MockHelpers.CreateClientInfo());

                atItem.Secret = atItem.GetKey().ToString();
                app.UserTokenCacheInternal.Accessor.SaveAccessToken(atItem);

                // another cache entry for different uid. user count should be 2.

                MsalRefreshTokenCacheItem rtItem = new MsalRefreshTokenCacheItem(
                    MsalTestConstants.ProductionPrefCacheEnvironment,
                    MsalTestConstants.ClientId,
                    "someRT",
                    MockHelpers.CreateClientInfo("uId1", "uTId1"));

                app.UserTokenCacheInternal.Accessor.SaveRefreshToken(rtItem);

                MsalIdTokenCacheItem idTokenCacheItem = new MsalIdTokenCacheItem(
                    MsalTestConstants.ProductionPrefCacheEnvironment,
                    MsalTestConstants.ClientId,
                    MockHelpers.CreateIdToken(MsalTestConstants.UniqueId, MsalTestConstants.DisplayableId),
                    MockHelpers.CreateClientInfo("uId1", "uTId1"),
                    "uTId1");

                app.UserTokenCacheInternal.Accessor.SaveIdToken(idTokenCacheItem);

                MsalAccountCacheItem accountCacheItem = new MsalAccountCacheItem(
                    MsalTestConstants.ProductionPrefCacheEnvironment,
                    null,
                    MockHelpers.CreateClientInfo("uId1", "uTId1"),
                    null,
                    null,
                    "uTId1",
                    null,
                    null);

                app.UserTokenCacheInternal.Accessor.SaveAccount(accountCacheItem);

                Assert.AreEqual(2, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count());
                accounts = app.GetAccountsAsync().Result;
                Assert.IsNotNull(accounts);
                Assert.AreEqual(2, accounts.Count()); // scoped by env

                // another cache entry for different environment. user count should still be 2. Sovereign cloud user must not be returned
                rtItem = new MsalRefreshTokenCacheItem(
                    MsalTestConstants.SovereignNetworkEnvironment,
                    MsalTestConstants.ClientId,
                    "someRT",
                    MockHelpers.CreateClientInfo(MsalTestConstants.Uid + "more1", MsalTestConstants.Utid));

                app.UserTokenCacheInternal.Accessor.SaveRefreshToken(rtItem);
                Assert.AreEqual(3, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count());
                accounts = app.GetAccountsAsync().Result;
                Assert.IsNotNull(accounts);
                Assert.AreEqual(2, accounts.Count());
            }
        }
        public void SaveAccessToken(MsalAccessTokenCacheItem item)
        {
            IiOSKey key = item.GetKey();

            Save(key, item.ToJsonString());
        }
Exemple #30
0
        public void NoCacheLookup()
        {
            MyReceiver myReceiver = new MyReceiver();

            using (MockHttpAndServiceBundle harness = CreateTestHarness(telemetryCallback: myReceiver.HandleTelemetryEvents))
            {
                TokenCache cache = new TokenCache(harness.ServiceBundle, false);

                MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem(
                    TestConstants.ProductionPrefNetworkEnvironment,
                    TestConstants.ClientId,
                    TestConstants.s_scope.AsSingleString(),
                    TestConstants.Utid,
                    null,
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(7200)),
                    MockHelpers.CreateClientInfo());

                string atKey = atItem.GetKey().ToString();
                atItem.Secret = atKey;
                ((ITokenCacheInternal)cache).Accessor.SaveAccessToken(atItem);

                MockWebUI ui = new MockWebUI()
                {
                    MockResult = AuthorizationResult.FromUri(TestConstants.AuthorityHomeTenant + "?code=some-code")
                };

                MockInstanceDiscoveryAndOpenIdRequest(harness.HttpManager);

                harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityHomeTenant);

                AuthenticationRequestParameters parameters = harness.CreateAuthenticationRequestParameters(
                    TestConstants.AuthorityHomeTenant,
                    TestConstants.s_scope,
                    cache,
                    extraQueryParameters: new Dictionary <string, string>
                {
                    { "extra", "qp" }
                });
                parameters.RedirectUri = new Uri("some://uri");
                parameters.LoginHint   = TestConstants.DisplayableId;
                AcquireTokenInteractiveParameters interactiveParameters = new AcquireTokenInteractiveParameters
                {
                    Prompt = Prompt.SelectAccount,
                    ExtraScopesToConsent = TestConstants.s_scopeForAnotherResource.ToArray(),
                };

                InteractiveRequest request = new InteractiveRequest(
                    harness.ServiceBundle,
                    parameters,
                    interactiveParameters,
                    ui);

                Task <AuthenticationResult> task = request.RunAsync(CancellationToken.None);
                task.Wait();
                AuthenticationResult result = task.Result;
                Assert.IsNotNull(result);
                Assert.AreEqual(1, ((ITokenCacheInternal)cache).Accessor.GetAllRefreshTokens().Count());
                Assert.AreEqual(2, ((ITokenCacheInternal)cache).Accessor.GetAllAccessTokens().Count());
                Assert.AreEqual(result.AccessToken, "some-access-token");

                Assert.IsNotNull(
                    myReceiver.EventsReceived.Find(
                        anEvent => // Expect finding such an event
                        anEvent[EventBase.EventNameKey].EndsWith("ui_event") &&
                        anEvent[UiEvent.UserCancelledKey] == "false"));
                Assert.IsNotNull(
                    myReceiver.EventsReceived.Find(
                        anEvent => // Expect finding such an event
                        anEvent[EventBase.EventNameKey].EndsWith("api_event") &&
                        anEvent[ApiEvent.PromptKey] == "select_account"));
                Assert.IsNotNull(
                    myReceiver.EventsReceived.Find(
                        anEvent => // Expect finding such an event
                        anEvent[EventBase.EventNameKey].EndsWith("ui_event") &&
                        anEvent[UiEvent.AccessDeniedKey] == "false"));
            }
        }