示例#1
0
        public void SaveAccount(MsalAccountCacheItem item)
        {
            ISharedPreferencesEditor editor = _accountSharedPreference.Edit();

            editor.PutString(item.GetKey().ToString(), item.ToJsonString());
            editor.Apply();
        }
示例#2
0
        public void SaveAccount(MsalAccountCacheItem item)
        {
            ApplicationDataCompositeValue composite = new ApplicationDataCompositeValue();

            SetCacheValue(composite, JsonHelper.SerializeToJson(item));
            _accountContainer.Values[/*CoreCryptographyHelpers.CreateBase64UrlEncodedSha256Hash(cacheKey)*/ item.GetKey().ToString()] = composite;
        }
示例#3
0
        public static void AddAccountToCache(ITokenCacheAccessor accessor, string uid, string utid)
        {
            MsalAccountCacheItem accountCacheItem = new MsalAccountCacheItem
                                                        (MsalTestConstants.ProductionPrefCacheEnvironment, null, MockHelpers.CreateClientInfo(uid, utid), null, null, utid, null, null);

            accessor.SaveAccount(accountCacheItem);
        }
        public void TestSerializeMsalAccountCacheItem()
        {
            var    item   = CreateAccountItem();
            string asJson = item.ToJsonString();
            var    item2  = MsalAccountCacheItem.FromJsonString(asJson);

            AssertAccountCacheItemsAreEqual(item, item2);
        }
示例#5
0
        public void SaveAccount(MsalAccountCacheItem item)
        {
            string itemKey      = item.GetKey().ToString();
            string partitionKey = CacheKeyFactory.GetKeyFromCachedItem(item);

            AccountCacheDictionary
            .GetOrAdd(partitionKey, new ConcurrentDictionary <string, MsalAccountCacheItem>())[itemKey] = item;
        }
示例#6
0
        private bool RtMatchesAccount(MsalRefreshTokenCacheItem rtItem, MsalAccountCacheItem account)
        {
            bool homeAccIdMatch = rtItem.HomeAccountId.Equals(account.HomeAccountId, StringComparison.OrdinalIgnoreCase);
            bool clientIdMatch  =
                rtItem.IsFRT || // Cannot filter by client ID if the RT can be used by multiple clients
                rtItem.ClientId.Equals(ClientId, StringComparison.OrdinalIgnoreCase);

            return(homeAccIdMatch && clientIdMatch);
        }
示例#7
0
        public MsalAccountCacheItem GetAccount(MsalAccountCacheKey accountKey)
        {
            string partitionKey = CacheKeyFactory.GetKeyFromAccount(accountKey);

            AccountCacheDictionary.TryGetValue(partitionKey, out var partition);
            MsalAccountCacheItem cacheItem = null;

            partition?.TryGetValue(accountKey.ToString(), out cacheItem);
            return(cacheItem);
        }
示例#8
0
 public void SaveAccount(MsalAccountCacheItem item, RequestContext requestContext)
 {
     using (TelemetryManager.CreateTelemetryHelper(requestContext.TelemetryRequestId, requestContext.ClientId,
                                                   new CacheEvent(CacheEvent.TokenCacheWrite)
     {
         TokenType = CacheEvent.TokenTypes.ACCOUNT
     }))
     {
         SaveAccount(item);
     }
 }
        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);
        }
示例#10
0
        internal MsalUserRefreshTokenControl(PublicClientApplication publicClient, MsalRefreshTokenCacheItem rtIitem) : this()
        {
            this.publicClient = publicClient;
            cache             = publicClient.UserTokenCache;
            rtItem            = rtIitem;

            accountItem   = cache.GetAccount(rtIitem, new RequestContext(null, new MsalLogger(Guid.NewGuid(), null)));
            upnLabel.Text = accountItem.PreferredUsername;

            invalidateRefreshTokenBtn.Enabled = !rtItem.Secret.Equals(GarbageRtValue, StringComparison.OrdinalIgnoreCase);
        }
示例#11
0
        private void AssertAccountCacheItemsAreEqual(MsalAccountCacheItem expected, MsalAccountCacheItem actual)
        {
            AssertCacheItemBaseItemsAreEqual(expected, actual);

            Assert.AreEqual(expected.PreferredUsername, actual.PreferredUsername, nameof(actual.PreferredUsername));
            Assert.AreEqual(expected.Name, actual.Name, nameof(actual.Name));
            Assert.AreEqual(expected.GivenName, actual.GivenName, nameof(actual.GivenName));
            Assert.AreEqual(expected.FamilyName, actual.FamilyName, nameof(actual.FamilyName));
            Assert.AreEqual(expected.LocalAccountId, actual.LocalAccountId, nameof(actual.LocalAccountId));
            Assert.AreEqual(expected.AuthorityType, actual.AuthorityType, nameof(actual.AuthorityType));
            Assert.AreEqual(expected.TenantId, actual.TenantId, nameof(actual.TenantId));
        }
示例#12
0
        private void MergeWamAccountIds(MsalAccountCacheItem msalAccountCacheItem)
        {
            var existingAccount = _accessor.GetAllAccounts()
                                  .SingleOrDefault(
                acc => string.Equals(
                    acc.GetKey().ToString(),
                    msalAccountCacheItem.GetKey().ToString(),
                    StringComparison.OrdinalIgnoreCase));
            var existingWamAccountIds = existingAccount?.WamAccountIds;

            msalAccountCacheItem.WamAccountIds.MergeDifferentEntries(existingWamAccountIds);
        }
示例#13
0
        public void DeleteAccount(MsalAccountCacheItem item)
        {
            string partitionKey = CacheKeyFactory.GetKeyFromCachedItem(item);

            AccountCacheDictionary.TryGetValue(partitionKey, out var partition);
            if (partition == null || !partition.TryRemove(item.GetKey().ToString(), out _))
            {
                _logger.InfoPii(
                    $"Cannot delete account because it was not found in the cache. Key {item.GetKey()}.",
                    "Cannot delete account because it was not found in the cache");
            }
        }
        public void SaveAccount(MsalAccountCacheItem item)
        {
            var key     = item.GetKey();
            var account = key.GetiOSAccountKey();
            var service = key.GetiOSServiceKey();
            var generic = key.GetiOSGenericKey();

            var type = AuthorityTypeToAttrType[item.AuthorityType];

            var value = JsonHelper.SerializeToJson(item);

            Save(account, service, generic, type, value);
        }
        private void AssertAccountCacheItemsAreEqual(MsalAccountCacheItem expected, MsalAccountCacheItem actual)
        {
            AssertCacheItemBaseItemsAreEqual(expected, actual);

            Assert.AreEqual(expected.PreferredUsername, actual.PreferredUsername, nameof(actual.PreferredUsername));
            Assert.AreEqual(expected.Name, actual.Name, nameof(actual.Name));
            Assert.AreEqual(expected.GivenName, actual.GivenName, nameof(actual.GivenName));
            Assert.AreEqual(expected.FamilyName, actual.FamilyName, nameof(actual.FamilyName));
            Assert.AreEqual(expected.LocalAccountId, actual.LocalAccountId, nameof(actual.LocalAccountId));
            Assert.AreEqual(expected.AuthorityType, actual.AuthorityType, nameof(actual.AuthorityType));
            Assert.AreEqual(expected.TenantId, actual.TenantId, nameof(actual.TenantId));
            CoreAssert.AssertDictionariesAreEqual(expected.WamAccountIds, actual.WamAccountIds, StringComparer.Ordinal);
        }
        internal static (MsalAccessTokenCacheItem AT, MsalRefreshTokenCacheItem RT, MsalIdTokenCacheItem ID, MsalAccountCacheItem Account) PopulateCacheWithOneAccessToken(ITokenCacheAccessor accessor, bool randomizeClientInfo = false)
        {
            string uid  = randomizeClientInfo ? Guid.NewGuid().ToString() : TestConstants.Uid;
            string utid = randomizeClientInfo ? Guid.NewGuid().ToString() : TestConstants.Utid;

            string clientInfo    = MockHelpers.CreateClientInfo(uid, utid);
            string homeAccountId = ClientInfo.CreateFromJson(clientInfo).ToAccountIdentifier();

            MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem(
                TestConstants.ProductionPrefCacheEnvironment,
                TestConstants.ClientId,
                TestConstants.s_scope.AsSingleString(),
                TestConstants.Utid,
                "",
                DateTimeOffset.UtcNow,
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn)),
                clientInfo,
                homeAccountId);

            // add access token
            accessor.SaveAccessToken(atItem);

            MsalIdTokenCacheItem idTokenCacheItem = new MsalIdTokenCacheItem(
                TestConstants.ProductionPrefCacheEnvironment,
                TestConstants.ClientId,
                MockHelpers.CreateIdToken(TestConstants.UniqueId + "more", TestConstants.DisplayableId),
                clientInfo,
                homeAccountId,
                TestConstants.Utid);

            accessor.SaveIdToken(idTokenCacheItem);

            MsalAccountCacheItem accountCacheItem = new MsalAccountCacheItem(
                TestConstants.ProductionPrefNetworkEnvironment,
                null,
                clientInfo,
                homeAccountId,
                null,
                null,
                TestConstants.Utid,
                null,
                null,
                null);

            accessor.SaveAccount(accountCacheItem);
            var rt = AddRefreshTokenToCache(accessor, uid, utid);

            return(atItem, rt, idTokenCacheItem, accountCacheItem);
        }
        internal AccountCacheItemDetails(MsalAccountCacheItem msalAccountCacheItem)
        {
            InitializeComponent();

            authorityTypeLabel.Text     = msalAccountCacheItem.AuthorityType;
            environmentLabel.Text       = msalAccountCacheItem.Environment;
            userIdentifierLabel.Text    = msalAccountCacheItem.HomeAccountId;
            preferredUsernameLabel.Text = msalAccountCacheItem.PreferredUsername;

            localAccountIdLabel.Text = msalAccountCacheItem.LocalAccountId;

            rawClientInfoLabel.Text = msalAccountCacheItem.RawClientInfo;
            clientInfoUniqueIdentifierLabel.Text       = msalAccountCacheItem.ClientInfo.UniqueObjectIdentifier;
            clientInfoUniqueTenantIdentifierLabel.Text = msalAccountCacheItem.ClientInfo.UniqueTenantIdentifier;
        }
        internal static void PopulateCache(ITokenCacheAccessor accessor)
        {
            MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem(
                CoreTestConstants.ProductionPrefCacheEnvironment,
                CoreTestConstants.ClientId,
                "Bearer",
                CoreTestConstants.Scope.AsSingleString(),
                CoreTestConstants.Utid,
                "",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn)),
                MockHelpers.CreateClientInfo());

            // add access token
            accessor.SaveAccessToken(atItem);

            MsalIdTokenCacheItem idTokenCacheItem = new MsalIdTokenCacheItem(
                CoreTestConstants.ProductionPrefCacheEnvironment, CoreTestConstants.ClientId,
                MockHelpers.CreateIdToken(CoreTestConstants.UniqueId + "more", CoreTestConstants.DisplayableId),
                MockHelpers.CreateClientInfo(), CoreTestConstants.Utid);

            accessor.SaveIdToken(idTokenCacheItem);

            MsalAccountCacheItem accountCacheItem = new MsalAccountCacheItem
                                                        (CoreTestConstants.ProductionPrefNetworkEnvironment, null, MockHelpers.CreateClientInfo(), null, null, CoreTestConstants.Utid,
                                                        null, null);

            accessor.SaveAccount(accountCacheItem);

            atItem = new MsalAccessTokenCacheItem(
                CoreTestConstants.ProductionPrefCacheEnvironment,
                CoreTestConstants.ClientId,
                "Bearer",
                CoreTestConstants.ScopeForAnotherResource.AsSingleString(),
                CoreTestConstants.Utid,
                "",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn)),
                MockHelpers.CreateClientInfo());

            // add another access token
            accessor.SaveAccessToken(atItem);

            AddRefreshTokenToCache(accessor, CoreTestConstants.Uid, CoreTestConstants.Utid, CoreTestConstants.Name);
        }
        internal void PopulateCacheWithOneAccessToken(ITokenCacheAccessor accessor)
        {
            string clientInfo    = MockHelpers.CreateClientInfo();
            string homeAccountId = ClientInfo.CreateFromJson(clientInfo).ToAccountIdentifier();

            MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem(
                TestConstants.ProductionPrefCacheEnvironment,
                TestConstants.ClientId,
                TestConstants.s_scope.AsSingleString(),
                TestConstants.Utid,
                "",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn)),
                clientInfo,
                homeAccountId);

            // add access token
            accessor.SaveAccessToken(atItem);

            MsalIdTokenCacheItem idTokenCacheItem = new MsalIdTokenCacheItem(
                TestConstants.ProductionPrefCacheEnvironment,
                TestConstants.ClientId,
                MockHelpers.CreateIdToken(TestConstants.UniqueId + "more", TestConstants.DisplayableId),
                clientInfo,
                homeAccountId,
                TestConstants.Utid);

            accessor.SaveIdToken(idTokenCacheItem);

            MsalAccountCacheItem accountCacheItem = new MsalAccountCacheItem(
                TestConstants.ProductionPrefNetworkEnvironment,
                null,
                clientInfo,
                homeAccountId,
                null,
                null,
                TestConstants.Utid,
                null,
                null,
                null);

            accessor.SaveAccount(accountCacheItem);
            AddRefreshTokenToCache(accessor, TestConstants.Uid, TestConstants.Utid);
        }
        public void TestSerializeAccountWithWamId()
        {
            MsalAccountCacheItem item = CreateAccountItem();

            item.WamAccountIds = new Dictionary <string, string>()
            {
                { "client_id_1", "wam_id_1" }, { "client_id_2", "wam_id_2" }
            };
            string asJson = item.ToJsonString();

            Assert.IsTrue(asJson.Contains(@" ""wam_account_ids"": {
    ""client_id_1"": ""wam_id_1"",
    ""client_id_2"": ""wam_id_2""
  }"));

            var item2 = MsalAccountCacheItem.FromJsonString(asJson);

            AssertAccountCacheItemsAreEqual(item, item2);
        }
示例#21
0
        internal MsalUserRefreshTokenControl(PublicClientApplication publicClient, MsalRefreshTokenCacheItem rtItem) : this()
        {
            _publicClient = publicClient;
            _cache        = publicClient.UserTokenCacheInternal;
            _rtItem       = rtItem;

            foreach (var acc in _cache.Accessor.GetAllAccounts())
            {
                if (_rtItem.HomeAccountId.Equals(acc.HomeAccountId, StringComparison.OrdinalIgnoreCase) &&
                    _rtItem.Environment.Equals(acc.Environment, StringComparison.OrdinalIgnoreCase))
                {
                    _accountItem = acc;
                }
            }

            upnLabel.Text = _accountItem?.PreferredUsername;

            invalidateRefreshTokenBtn.Enabled = !_rtItem.Secret.Equals(GarbageRtValue, StringComparison.OrdinalIgnoreCase);
        }
        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;
        }
        public void TestSerializeMsalAccountCacheItemWithAdditionalFields()
        {
            var item = CreateAccountItem();

            // Add an unknown field into the json
            var asJObject = item.ToJObject();

            asJObject["unsupported_field_name"] = "this is a value";

            // Ensure unknown field remains in the AdditionalFieldsJson block
            var item2 = MsalAccountCacheItem.FromJObject(asJObject);

            Assert.AreEqual("{\r\n  \"unsupported_field_name\": \"this is a value\"\r\n}", item2.AdditionalFieldsJson);

            // Ensure additional fields make the round trip into json
            asJObject = item2.ToJObject();
            AssertAccountHasJObjectFields(
                asJObject,
                new List <string>
            {
                "unsupported_field_name"
            });
        }
        public void TestMsalNet2XCacheSerializationInterop()
        {
            var    accessor    = new InMemoryTokenCacheAccessor(Substitute.For <ICoreLogger>());
            var    s           = new TokenCacheDictionarySerializer(accessor);
            string binFilePath = ResourceHelper.GetTestResourceRelativePath("cachecompat_dotnet_dictionary.bin");

            byte[] bytes = File.ReadAllBytes(binFilePath);
            s.Deserialize(bytes, false);

            Assert.AreEqual(1, accessor.GetAllAccessTokens().Count());
            Assert.AreEqual(1, accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(1, accessor.GetAllIdTokens().Count());
            Assert.AreEqual(1, accessor.GetAllAccounts().Count());
            Assert.AreEqual(0, accessor.GetAllAppMetadata().Count());

            var expectedAccessTokenItem = new MsalAccessTokenCacheItem("User.Read User.ReadBasic.All profile openid email")
            {
                AdditionalFieldsJson           = "{\r\n  \"access_token_type\": \"Bearer\"\r\n}",
                Environment                    = "login.windows.net",
                HomeAccountId                  = "13dd2c19-84cd-416a-ae7d-49573e425619.26039cce-489d-4002-8293-5b0c5134eacb",
                RawClientInfo                  = string.Empty,
                ClientId                       = "b945c513-3946-4ecd-b179-6499803a2167",
                TenantId                       = "26039cce-489d-4002-8293-5b0c5134eacb",
                CachedAt                       = "1548803419",
                ExpiresOnUnixTimestamp         = "1548846619",
                ExtendedExpiresOnUnixTimestamp = "1548846619",
                UserAssertionHash              = string.Empty,
                TokenType                      = StorageJsonValues.TokenTypeBearer
            };

            AssertAccessTokenCacheItemsAreEqual(expectedAccessTokenItem, accessor.GetAllAccessTokens().First());

            var expectedRefreshTokenItem = new MsalRefreshTokenCacheItem
            {
                Environment   = "login.windows.net",
                HomeAccountId = "13dd2c19-84cd-416a-ae7d-49573e425619.26039cce-489d-4002-8293-5b0c5134eacb",
                RawClientInfo = string.Empty,
                ClientId      = "b945c513-3946-4ecd-b179-6499803a2167"
            };

            AssertRefreshTokenCacheItemsAreEqual(expectedRefreshTokenItem, accessor.GetAllRefreshTokens().First());

            var expectedIdTokenItem = new MsalIdTokenCacheItem
            {
                Environment   = "login.windows.net",
                HomeAccountId = "13dd2c19-84cd-416a-ae7d-49573e425619.26039cce-489d-4002-8293-5b0c5134eacb",
                RawClientInfo = string.Empty,
                ClientId      = "b945c513-3946-4ecd-b179-6499803a2167",
                TenantId      = "26039cce-489d-4002-8293-5b0c5134eacb"
            };

            AssertIdTokenCacheItemsAreEqual(expectedIdTokenItem, accessor.GetAllIdTokens().First());

            var expectedAccountItem = new MsalAccountCacheItem
            {
                Environment       = "login.windows.net",
                HomeAccountId     = "13dd2c19-84cd-416a-ae7d-49573e425619.26039cce-489d-4002-8293-5b0c5134eacb",
                RawClientInfo     = "eyJ1aWQiOiIxM2RkMmMxOS04NGNkLTQxNmEtYWU3ZC00OTU3M2U0MjU2MTkiLCJ1dGlkIjoiMjYwMzljY2UtNDg5ZC00MDAyLTgyOTMtNWIwYzUxMzRlYWNiIn0",
                PreferredUsername = "******",
                Name           = "Abhi Test",
                GivenName      = string.Empty,
                FamilyName     = string.Empty,
                LocalAccountId = "13dd2c19-84cd-416a-ae7d-49573e425619",
                TenantId       = "26039cce-489d-4002-8293-5b0c5134eacb"
            };

            AssertAccountCacheItemsAreEqual(expectedAccountItem, accessor.GetAllAccounts().First());
        }
示例#25
0
        public void TestMsalAccountCacheItemFromJsonStringEmpty()
        {
            var item = MsalAccountCacheItem.FromJsonString(null);

            Assert.IsNull(item);
        }
示例#26
0
        internal void PopulateCache(
            ITokenCacheAccessor accessor,
            string uid      = MsalTestConstants.Uid,
            string utid     = MsalTestConstants.Utid,
            string clientId = MsalTestConstants.ClientId)
        {
            MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem(
                MsalTestConstants.ProductionPrefCacheEnvironment,
                clientId,
                MsalTestConstants.Scope.AsSingleString(),
                utid,
                "",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn)),
                MockHelpers.CreateClientInfo(uid, utid));

            // add access token
            accessor.SaveAccessToken(atItem);

            var idTokenCacheItem = new MsalIdTokenCacheItem(
                MsalTestConstants.ProductionPrefCacheEnvironment,
                clientId,
                MockHelpers.CreateIdToken(MsalTestConstants.UniqueId + "more", MsalTestConstants.DisplayableId),
                MockHelpers.CreateClientInfo(uid, utid),
                utid);

            accessor.SaveIdToken(idTokenCacheItem);

            var accountCacheItem = new MsalAccountCacheItem(
                MsalTestConstants.ProductionPrefCacheEnvironment,
                null,
                MockHelpers.CreateClientInfo(uid, utid),
                null,
                MsalTestConstants.DisplayableId,
                utid,
                null,
                null);

            accessor.SaveAccount(accountCacheItem);

            atItem = new MsalAccessTokenCacheItem(
                MsalTestConstants.ProductionPrefCacheEnvironment,
                clientId,
                MsalTestConstants.ScopeForAnotherResource.AsSingleString(),
                utid,
                "",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn)),
                MockHelpers.CreateClientInfo(uid, utid));

            // add another access token
            accessor.SaveAccessToken(atItem);

            AddRefreshTokenToCache(accessor, uid, utid, clientId);

            var appMetadataItem = new MsalAppMetadataCacheItem(
                clientId,
                MsalTestConstants.ProductionPrefCacheEnvironment,
                null);

            accessor.SaveAppMetadata(appMetadataItem);
        }
示例#27
0
        async Task <Tuple <MsalAccessTokenCacheItem, MsalIdTokenCacheItem, Account> > ITokenCacheInternal.SaveTokenResponseAsync(
            AuthenticationRequestParameters requestParams,
            MsalTokenResponse response)
        {
            response.Log(requestParams.RequestContext.Logger, LogLevel.Verbose);

            MsalAccessTokenCacheItem  msalAccessTokenCacheItem  = null;
            MsalRefreshTokenCacheItem msalRefreshTokenCacheItem = null;
            MsalIdTokenCacheItem      msalIdTokenCacheItem      = null;
            MsalAccountCacheItem      msalAccountCacheItem      = null;

            IdToken idToken = IdToken.Parse(response.IdToken);

            if (idToken == null)
            {
                requestParams.RequestContext.Logger.Info("ID Token not present in response. ");
            }

            var tenantId = GetTenantId(idToken, requestParams);

            bool   isAdfsAuthority      = requestParams.AuthorityInfo.AuthorityType == AuthorityType.Adfs;
            string preferredUsername    = GetPreferredUsernameFromIdToken(isAdfsAuthority, idToken);
            string username             = isAdfsAuthority ? idToken?.Upn : preferredUsername;
            string homeAccountId        = GetHomeAccountId(requestParams, response, idToken);
            string suggestedWebCacheKey = SuggestedWebCacheKeyFactory.GetKeyFromResponse(requestParams, homeAccountId);

            // Do a full instance discovery when saving tokens (if not cached),
            // so that the PreferredNetwork environment is up to date.
            var instanceDiscoveryMetadata = await ServiceBundle.InstanceDiscoveryManager
                                            .GetMetadataEntryAsync(
                requestParams.Authority.AuthorityInfo,
                requestParams.RequestContext)
                                            .ConfigureAwait(false);

            #region Create Cache Objects
            if (!string.IsNullOrEmpty(response.AccessToken))
            {
                msalAccessTokenCacheItem =
                    new MsalAccessTokenCacheItem(
                        instanceDiscoveryMetadata.PreferredCache,
                        requestParams.AppConfig.ClientId,
                        response,
                        tenantId,
                        homeAccountId,
                        requestParams.AuthenticationScheme.KeyId)
                {
                    UserAssertionHash = requestParams.UserAssertion?.AssertionHash,
                    IsAdfs            = isAdfsAuthority
                };
            }

            if (!string.IsNullOrEmpty(response.RefreshToken))
            {
                msalRefreshTokenCacheItem = new MsalRefreshTokenCacheItem(
                    instanceDiscoveryMetadata.PreferredCache,
                    requestParams.AppConfig.ClientId,
                    response,
                    homeAccountId);

                if (!_featureFlags.IsFociEnabled)
                {
                    msalRefreshTokenCacheItem.FamilyId = null;
                }
            }

            Dictionary <string, string> wamAccountIds = GetWamAccountIds(requestParams, response);
            Account account;
            if (idToken != null)
            {
                msalIdTokenCacheItem = new MsalIdTokenCacheItem(
                    instanceDiscoveryMetadata.PreferredCache,
                    requestParams.AppConfig.ClientId,
                    response,
                    tenantId,
                    homeAccountId)
                {
                    IsAdfs = isAdfsAuthority
                };

                msalAccountCacheItem = new MsalAccountCacheItem(
                    instanceDiscoveryMetadata.PreferredCache,
                    response.ClientInfo,
                    homeAccountId,
                    idToken,
                    preferredUsername,
                    tenantId,
                    wamAccountIds);
            }

            #endregion

            account = new Account(
                homeAccountId,
                username,
                instanceDiscoveryMetadata.PreferredNetwork,
                wamAccountIds);
            requestParams.RequestContext.Logger.Verbose("[SaveTokenResponseAsync] Entering token cache semaphore. ");
            await _semaphoreSlim.WaitAsync().ConfigureAwait(false);

            requestParams.RequestContext.Logger.Verbose("[SaveTokenResponseAsync] Entered token cache semaphore. ");

            try
            {
#pragma warning disable CS0618 // Type or member is obsolete
                HasStateChanged = true;
#pragma warning restore CS0618 // Type or member is obsolete

                try
                {
                    ITokenCacheInternal tokenCacheInternal = this;
                    if (tokenCacheInternal.IsTokenCacheSerialized())
                    {
                        var args = new TokenCacheNotificationArgs(
                            this,
                            ClientId,
                            account,
                            hasStateChanged: true,
                            tokenCacheInternal.IsApplicationCache,
                            hasTokens: tokenCacheInternal.HasTokensNoLocks(),
                            requestParams.RequestContext.UserCancellationToken,
                            suggestedCacheKey: suggestedWebCacheKey);

                        Stopwatch sw = Stopwatch.StartNew();

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

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

                        requestParams.RequestContext.ApiEvent.DurationInCacheInMs += sw.ElapsedMilliseconds;
                    }

                    if (msalAccessTokenCacheItem != null)
                    {
                        requestParams.RequestContext.Logger.Info("Saving AT in cache and removing overlapping ATs...");

                        DeleteAccessTokensWithIntersectingScopes(
                            requestParams,
                            instanceDiscoveryMetadata.Aliases,
                            tenantId,
                            msalAccessTokenCacheItem.ScopeSet,
                            msalAccessTokenCacheItem.HomeAccountId,
                            msalAccessTokenCacheItem.TokenType);

                        _accessor.SaveAccessToken(msalAccessTokenCacheItem);
                    }

                    if (idToken != null)
                    {
                        requestParams.RequestContext.Logger.Info("Saving Id Token and Account in cache ...");
                        _accessor.SaveIdToken(msalIdTokenCacheItem);
                        MergeWamAccountIds(msalAccountCacheItem);
                        _accessor.SaveAccount(msalAccountCacheItem);
                    }

                    // if server returns the refresh token back, save it in the cache.
                    if (msalRefreshTokenCacheItem != null)
                    {
                        requestParams.RequestContext.Logger.Info("Saving RT in cache...");
                        _accessor.SaveRefreshToken(msalRefreshTokenCacheItem);
                    }

                    UpdateAppMetadata(requestParams.AppConfig.ClientId, instanceDiscoveryMetadata.PreferredCache, response.FamilyId);

                    // Do not save RT in ADAL cache for client credentials flow or B2C
                    if (ServiceBundle.Config.LegacyCacheCompatibilityEnabled &&
                        !requestParams.IsClientCredentialRequest &&
                        requestParams.AuthorityInfo.AuthorityType != AuthorityType.B2C)
                    {
                        var tenatedAuthority            = Authority.CreateAuthorityWithTenant(requestParams.AuthorityInfo, tenantId);
                        var authorityWithPreferredCache = Authority.CreateAuthorityWithEnvironment(
                            tenatedAuthority.AuthorityInfo,
                            instanceDiscoveryMetadata.PreferredCache);

                        CacheFallbackOperations.WriteAdalRefreshToken(
                            Logger,
                            LegacyCachePersistence,
                            msalRefreshTokenCacheItem,
                            msalIdTokenCacheItem,
                            authorityWithPreferredCache.AuthorityInfo.CanonicalAuthority,
                            msalIdTokenCacheItem.IdToken.ObjectId,
                            response.Scope);
                    }
                }
                finally
                {
                    ITokenCacheInternal tokenCacheInternal = this;
                    if (tokenCacheInternal.IsTokenCacheSerialized())
                    {
                        var args = new TokenCacheNotificationArgs(
                            this,
                            ClientId,
                            account,
                            hasStateChanged: true,
                            tokenCacheInternal.IsApplicationCache,
                            tokenCacheInternal.HasTokensNoLocks(),
                            requestParams.RequestContext.UserCancellationToken,
                            suggestedCacheKey: suggestedWebCacheKey);

                        Stopwatch sw = Stopwatch.StartNew();
                        await tokenCacheInternal.OnAfterAccessAsync(args).ConfigureAwait(false);

                        requestParams.RequestContext.ApiEvent.DurationInCacheInMs += sw.ElapsedMilliseconds;
                    }
#pragma warning disable CS0618 // Type or member is obsolete
                    HasStateChanged = false;
#pragma warning restore CS0618 // Type or member is obsolete
                }

                return(Tuple.Create(msalAccessTokenCacheItem, msalIdTokenCacheItem, account));
            }
            finally
            {
                _semaphoreSlim.Release();
                requestParams.RequestContext.Logger.Verbose("[SaveTokenResponseAsync] Released token cache semaphore. ");
            }
        }
示例#28
0
 public MsalAccountCacheItem GetAccount(MsalAccountCacheKey accountKey)
 {
     return(MsalAccountCacheItem.FromJsonString(_accountSharedPreference.GetString(accountKey.ToString(), null)));
 }
        async Task <Tuple <MsalAccessTokenCacheItem, MsalIdTokenCacheItem> > ITokenCacheInternal.SaveTokenResponseAsync(
            AuthenticationRequestParameters requestParams,
            MsalTokenResponse response)
        {
            var tenantId = Authority
                           .CreateAuthority(requestParams.TenantUpdatedCanonicalAuthority.AuthorityInfo.CanonicalAuthority)
                           .GetTenantId();

            bool isAdfsAuthority = requestParams.AuthorityInfo.AuthorityType == AuthorityType.Adfs;

            IdToken idToken = IdToken.Parse(response.IdToken);

            string subject = idToken?.Subject;

            if (idToken != null && string.IsNullOrEmpty(subject))
            {
                requestParams.RequestContext.Logger.Warning("Subject not present in Id token");
            }

            string preferredUsername = GetPreferredUsernameFromIdToken(isAdfsAuthority, idToken);

            // Do a full instance discovery when saving tokens (if not cached),
            // so that the PreferredNetwork environment is up to date.
            var instanceDiscoveryMetadata = await ServiceBundle.InstanceDiscoveryManager
                                            .GetMetadataEntryAsync(
                requestParams.TenantUpdatedCanonicalAuthority.AuthorityInfo.CanonicalAuthority,
                requestParams.RequestContext)
                                            .ConfigureAwait(false);

            var msalAccessTokenCacheItem =
                new MsalAccessTokenCacheItem(
                    instanceDiscoveryMetadata.PreferredCache,
                    requestParams.ClientId,
                    response,
                    tenantId,
                    subject,
                    requestParams.AuthenticationScheme.KeyId)
            {
                UserAssertionHash = requestParams.UserAssertion?.AssertionHash,
                IsAdfs            = isAdfsAuthority
            };

            MsalRefreshTokenCacheItem msalRefreshTokenCacheItem = null;
            MsalIdTokenCacheItem      msalIdTokenCacheItem      = null;

            if (idToken != null)
            {
                msalIdTokenCacheItem = new MsalIdTokenCacheItem(
                    instanceDiscoveryMetadata.PreferredCache,
                    requestParams.ClientId,
                    response,
                    tenantId,
                    subject)
                {
                    IsAdfs = isAdfsAuthority
                };
            }

            await _semaphoreSlim.WaitAsync().ConfigureAwait(false);

            try
            {
                try
                {
                    Account account  = null;
                    string  username = isAdfsAuthority ? idToken?.Upn : preferredUsername;
                    if (msalAccessTokenCacheItem.HomeAccountId != null)
                    {
                        account = new Account(
                            msalAccessTokenCacheItem.HomeAccountId,
                            username,
                            instanceDiscoveryMetadata.PreferredCache);
                    }
                    var args = new TokenCacheNotificationArgs(this, ClientId, account, true, (this as ITokenCacheInternal).IsApplicationCache);

#pragma warning disable CS0618 // Type or member is obsolete
                    HasStateChanged = true;
#pragma warning restore CS0618 // Type or member is obsolete

                    await(this as ITokenCacheInternal).OnBeforeAccessAsync(args).ConfigureAwait(false);
                    try
                    {
                        await(this as ITokenCacheInternal).OnBeforeWriteAsync(args).ConfigureAwait(false);

                        DeleteAccessTokensWithIntersectingScopes(
                            requestParams,
                            instanceDiscoveryMetadata.Aliases,
                            tenantId,
                            msalAccessTokenCacheItem.ScopeSet,
                            msalAccessTokenCacheItem.HomeAccountId,
                            msalAccessTokenCacheItem.TokenType);

                        _accessor.SaveAccessToken(msalAccessTokenCacheItem);

                        if (idToken != null)
                        {
                            _accessor.SaveIdToken(msalIdTokenCacheItem);
                            var msalAccountCacheItem = new MsalAccountCacheItem(
                                instanceDiscoveryMetadata.PreferredCache,
                                response,
                                preferredUsername,
                                tenantId);

                            //The ADFS direct scenario does not return client info so the home account id is acquired from the subject
                            if (isAdfsAuthority && String.IsNullOrEmpty(msalAccountCacheItem.HomeAccountId))
                            {
                                msalAccountCacheItem.HomeAccountId = idToken.Subject;
                            }

                            _accessor.SaveAccount(msalAccountCacheItem);
                        }

                        // if server returns the refresh token back, save it in the cache.
                        if (response.RefreshToken != null)
                        {
                            msalRefreshTokenCacheItem = new MsalRefreshTokenCacheItem(
                                instanceDiscoveryMetadata.PreferredCache,
                                requestParams.ClientId,
                                response,
                                subject);

                            if (!_featureFlags.IsFociEnabled)
                            {
                                msalRefreshTokenCacheItem.FamilyId = null;
                            }

                            requestParams.RequestContext.Logger.Info("Saving RT in cache...");
                            _accessor.SaveRefreshToken(msalRefreshTokenCacheItem);
                        }

                        UpdateAppMetadata(requestParams.ClientId, instanceDiscoveryMetadata.PreferredCache, response.FamilyId);

                        // save RT in ADAL cache for public clients
                        // do not save RT in ADAL cache for MSAL B2C scenarios
                        if (!requestParams.IsClientCredentialRequest && !requestParams.AuthorityInfo.AuthorityType.Equals(AuthorityType.B2C))
                        {
                            var authorityWithPrefferedCache = Authority.CreateAuthorityWithEnvironment(
                                requestParams.TenantUpdatedCanonicalAuthority.AuthorityInfo,
                                instanceDiscoveryMetadata.PreferredCache);

                            CacheFallbackOperations.WriteAdalRefreshToken(
                                Logger,
                                LegacyCachePersistence,
                                msalRefreshTokenCacheItem,
                                msalIdTokenCacheItem,
                                authorityWithPrefferedCache.AuthorityInfo.CanonicalAuthority,
                                msalIdTokenCacheItem.IdToken.ObjectId, response.Scope);
                        }
                    }
                    finally
                    {
                        await(this as ITokenCacheInternal).OnAfterAccessAsync(args).ConfigureAwait(false);
                    }

                    return(Tuple.Create(msalAccessTokenCacheItem, msalIdTokenCacheItem));
                }
                finally
                {
#pragma warning disable CS0618 // Type or member is obsolete
                    HasStateChanged = false;
#pragma warning restore CS0618 // Type or member is obsolete
                }
            }
            finally
            {
                _semaphoreSlim.Release();
            }
        }
        internal void PopulateCache(
            ITokenCacheAccessor accessor,
            string uid               = TestConstants.Uid,
            string utid              = TestConstants.Utid,
            string clientId          = TestConstants.ClientId,
            string environment       = TestConstants.ProductionPrefCacheEnvironment,
            string displayableId     = TestConstants.DisplayableId,
            string rtSecret          = TestConstants.RTSecret,
            string overridenScopes   = null,
            bool expiredAccessTokens = false,
            bool addSecondAt         = true)
        {
            string clientInfo = MockHelpers.CreateClientInfo(uid, utid);
            string homeAccId  = ClientInfo.CreateFromJson(clientInfo).ToAccountIdentifier();

            var accessTokenExpiresOn = expiredAccessTokens ?
                                       new DateTimeOffset(DateTime.UtcNow) :
                                       new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn));

            var extendedAccessTokenExpiresOn = expiredAccessTokens ?
                                               new DateTimeOffset(DateTime.UtcNow) :
                                               new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn));

            MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem(
                environment,
                clientId,
                overridenScopes ?? TestConstants.s_scope.AsSingleString(),
                utid,
                "",
                accessTokenExpiresOn,
                extendedAccessTokenExpiresOn,
                clientInfo,
                homeAccId);

            // add access token
            accessor.SaveAccessToken(atItem);

            var idTokenCacheItem = new MsalIdTokenCacheItem(
                environment,
                clientId,
                MockHelpers.CreateIdToken(TestConstants.UniqueId + "more", displayableId),
                clientInfo,
                homeAccId,
                tenantId: utid);

            accessor.SaveIdToken(idTokenCacheItem);

            // add another access token
            if (addSecondAt)
            {
                atItem = new MsalAccessTokenCacheItem(
                    environment,
                    clientId,
                    TestConstants.s_scopeForAnotherResource.AsSingleString(),
                    utid,
                    "",
                    accessTokenExpiresOn,
                    extendedAccessTokenExpiresOn,
                    clientInfo,
                    homeAccId);

                accessor.SaveAccessToken(atItem);
            }

            var accountCacheItem = new MsalAccountCacheItem(
                environment,
                null,
                clientInfo,
                homeAccId,
                null,
                displayableId,
                utid,
                null,
                null);

            accessor.SaveAccount(accountCacheItem);

            AddRefreshTokenToCache(accessor, uid, utid, clientId, environment, rtSecret);

            var appMetadataItem = new MsalAppMetadataCacheItem(
                clientId,
                environment,
                null);

            accessor.SaveAppMetadata(appMetadataItem);
        }