public void TestJsonSerialization()
        {
            string expectedJson = File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("ExpectedTokenCache.json"));
            var    accessor     = CreateTokenCacheAccessor();

            var s1 = new TokenCacheJsonSerializer(accessor);

            byte[] bytes      = s1.Serialize(null);
            string actualJson = new UTF8Encoding().GetString(bytes);

            Assert.IsTrue(JToken.DeepEquals(JObject.Parse(actualJson), JObject.Parse(expectedJson)));

            var otherAccessor = new InMemoryTokenCacheAccessor(Substitute.For <ICoreLogger>());
            var s2            = new TokenCacheJsonSerializer(otherAccessor);

            s2.Deserialize(bytes, false);

            AssertAccessorsAreEqual(accessor, otherAccessor);

            // serialize again to detect errors that come from deserialization
            byte[] bytes2      = s2.Serialize(null);
            string actualJson2 = new UTF8Encoding().GetString(bytes2);

            Assert.IsTrue(JToken.DeepEquals(JObject.Parse(actualJson2), JObject.Parse(expectedJson)));
        }
示例#2
0
        internal static void PopulateDefaultAppTokenCache(
            ConfidentialClientApplication app,
            MsalAccessTokenCacheItem atItem = null)
        {
            if (atItem == null)
            {
                atItem = CreateAccessTokenItem();
            }

            InMemoryTokenCacheAccessor accessor = new InMemoryTokenCacheAccessor(new NullLogger());

            accessor.SaveAccessToken(atItem);

            string key = SuggestedWebCacheKeyFactory.GetClientCredentialKey(atItem.ClientId, atItem.TenantId);

            byte[] bytes = new TokenCacheJsonSerializer(accessor).Serialize(null);
            app.InMemoryPartitionedCacheSerializer.CachePartition[key] = bytes;

            // force a cache read
            var args = new TokenCacheNotificationArgs(
                app.AppTokenCacheInternal,
                app.AppConfig.ClientId,
                null,
                hasStateChanged: false,
                true,
                hasTokens: true,
                suggestedCacheKey: key);

            app.AppTokenCacheInternal.OnBeforeAccessAsync(args).GetAwaiter().GetResult();
        }
        public void TestPythonCacheSerializationInterop()
        {
            var    accessor          = new InMemoryTokenCacheAccessor(Substitute.For <ICoreLogger>());
            var    s                 = new TokenCacheJsonSerializer(accessor);
            string pythonBinFilePath = ResourceHelper.GetTestResourceRelativePath("cachecompat_python.bin");

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

            Assert.AreEqual(0, accessor.GetAllAccessTokens().Count());
            Assert.AreEqual(0, accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(0, accessor.GetAllIdTokens().Count());
            Assert.AreEqual(0, accessor.GetAllAccounts().Count());
        }
        private ITokenCacheAccessor CreateTokenCacheAccessorWithKeyPrefix(
            string keyPrefix,
            int numAccessTokens,
            int numRefreshTokens,
            int numIdTokens,
            int numAccounts)
        {
            var accessor = new InMemoryTokenCacheAccessor(Substitute.For <ICoreLogger>());

            for (int i = 1; i <= numAccessTokens; i++)
            {
                var item = CreateAccessTokenItem();
                item.Environment = item.Environment + $"_{keyPrefix}{i}"; // ensure we get unique cache keys
                accessor.SaveAccessToken(item);
            }

            for (int i = 1; i <= numRefreshTokens; i++)
            {
                var item = CreateRefreshTokenItem();
                item.Environment = item.Environment + $"_{keyPrefix}{i}"; // ensure we get unique cache keys
                accessor.SaveRefreshToken(item);
            }

            // Create an FRT
            var frt = CreateRefreshTokenItem();

            frt.FamilyId = "1";
            accessor.SaveRefreshToken(frt);

            for (int i = 1; i <= numIdTokens; i++)
            {
                var item = CreateIdTokenItem();
                item.Environment = item.Environment + $"_{keyPrefix}{i}"; // ensure we get unique cache keys
                accessor.SaveIdToken(item);
            }

            for (int i = 1; i <= numAccounts; i++)
            {
                var item = CreateAccountItem();
                item.Environment = item.Environment + $"_{keyPrefix}{i}"; // ensure we get unique cache keys
                accessor.SaveAccount(item);
            }

            accessor.SaveAppMetadata(new MsalAppMetadataCacheItem(TestConstants.ClientId, "env_1", "1"));
            accessor.SaveAppMetadata(new MsalAppMetadataCacheItem(TestConstants.ClientId, "env_2", ""));
            accessor.SaveAppMetadata(new MsalAppMetadataCacheItem(TestConstants.ClientId2, "env_1", "another_family"));

            return(accessor);
        }
        public void TestDictionarySerialization()
        {
            var accessor = CreateTokenCacheAccessor();

            var s1 = new TokenCacheDictionarySerializer(accessor);

            byte[] bytes = s1.Serialize(null);
            string json  = new UTF8Encoding().GetString(bytes);

            var otherAccessor = new InMemoryTokenCacheAccessor(Substitute.For <ICoreLogger>());
            var s2            = new TokenCacheDictionarySerializer(otherAccessor);

            s2.Deserialize(bytes, false);

            AssertAccessorsAreEqual(accessor, otherAccessor);
        }
        public void TestDictionarySerialization()
        {
            var accessor = CreateTokenCacheAccessor();

            var s1 = new TokenCacheDictionarySerializer(accessor);

            byte[] bytes = s1.Serialize(null);
            string json  = new UTF8Encoding().GetString(bytes);

            // TODO(cache): assert json value?  or look at JObject?

            var otherAccessor = new InMemoryTokenCacheAccessor();
            var s2            = new TokenCacheDictionarySerializer(otherAccessor);

            s2.Deserialize(bytes, false);

            AssertAccessorsAreEqual(accessor, otherAccessor);
        }
        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());
        }
        private void PopulateAppCache(ConfidentialClientApplication cca, TokenDifference tokenDifference, int size)
        {
            Dictionary <string, InMemoryTokenCacheAccessor> accessors = new Dictionary <string, InMemoryTokenCacheAccessor>();
            string key = "";

            for (int i = 0; i < size; i++)
            {
                string tenantId = "tid";
                string scope    = "scope";

                switch (tokenDifference)
                {
                case TokenDifference.ByScope:
                    scope = $"scope_{i}";
                    break;

                case TokenDifference.ByTenant:
                    tenantId = $"tid_{i}";
                    break;

                default:
                    throw new NotImplementedException();
                }

                MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem(
                    TestConstants.ProductionPrefCacheEnvironment,
                    TestConstants.ClientId,
                    scope,
                    tenantId,
                    "",
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3600)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3600)),
                    null,
                    null);

                key = SuggestedWebCacheKeyFactory.GetClientCredentialKey(atItem.ClientId, atItem.TenantId);
                InMemoryTokenCacheAccessor accessor;
                if (!accessors.TryGetValue(key, out accessor))
                {
                    accessor       = new InMemoryTokenCacheAccessor(new NullLogger());
                    accessors[key] = accessor;
                }

                accessor.SaveAccessToken(atItem);

                if (tokenDifference == TokenDifference.ByTenant || (tokenDifference == TokenDifference.ByScope && i == size - 1))
                {
                    byte[] bytes = new TokenCacheJsonSerializer(accessor).Serialize(null);
                    cca.InMemoryPartitionedCacheSerializer.CachePartition[key] = bytes;
                }
            }

            // force a cache read, otherwise MSAL won't have the tokens in memory
            // force a cache read
            var args = new TokenCacheNotificationArgs(
                cca.AppTokenCacheInternal,
                cca.AppConfig.ClientId,
                null,
                hasStateChanged: false,
                true,
                hasTokens: true,
                cancellationToken: CancellationToken.None,
                suggestedCacheKey: key);

            cca.AppTokenCacheInternal.OnBeforeAccessAsync(args).GetAwaiter().GetResult();
        }