Exemplo n.º 1
0
        internal static void TokenCacheSerializationTest()
        {
            var       context      = new AuthenticationContext("https://login.windows.net/common", false);
            var       tokenCache   = context.TokenCache;
            const int MaxItemCount = 100;
            const int MaxFieldSize = 1024;

            for (int i = 0; i < 100; i++)
            {
                tokenCache.Clear();
                for (int count = 0; count < Rand.Next(1, MaxItemCount); count++)
                {
                    TokenCacheKey key = GenerateRandomTokenCacheKey();

                    AuthenticationResult result = GenerateRandomCacheValue(MaxFieldSize, key.UniqueId, key.DisplayableId);
                    AddToDictionary(tokenCache, key, result);
                }

                byte[]     serializedCache = tokenCache.Serialize();
                TokenCache cache2          = new TokenCache(serializedCache);
                foreach (var key in tokenCache.tokenCacheDictionary.Keys)
                {
                    AuthenticationResult result2 = cache2.tokenCacheDictionary[key];
                    VerifyAuthenticationResultsAreEqual(tokenCache.tokenCacheDictionary[key], result2);
                }
            }
        }
        //292916 Ensure AcquireTokenSilent tests exist in ADAL.NET for public clients
        public async Task ExpiredATValidRTInCache_GetNewATRTFromServiceAsync()
        {
            var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache());

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityCommonTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(),
                PostData        = new Dictionary <string, string>()
                {
                    { "client_id", TestConstants.DefaultClientId },
                    { "grant_type", "refresh_token" },
                    { "refresh_token", "some_rt" }
                }
            });

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityCommonTenant,
                                                  TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                  TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId);

            context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx
            {
                RefreshToken       = "some_rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token",
                                                              DateTimeOffset.UtcNow)
            };

            AuthenticationResult result = await context.AcquireTokenSilentAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                                                                new UserIdentifier(TestConstants.DefaultDisplayableId, UserIdentifierType.RequiredDisplayableId)).ConfigureAwait(false);

            Assert.IsNotNull(result);
        }
        public void AcquireTokenSilentServiceErrorTestAsync()
        {
            TokenCache    cache = new TokenCache();
            TokenCacheKey key   = new TokenCacheKey(TestConstants.DefaultAuthorityCommonTenant,
                                                    TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, "unique_id",
                                                    "*****@*****.**");

            cache.tokenCacheDictionary[key] = new AuthenticationResultEx
            {
                RefreshToken       = "something-invalid",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "some-access-token", DateTimeOffset.UtcNow)
            };

            AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, cache);

            var ex = AssertException.TaskThrows <AdalSilentTokenAcquisitionException>(async() =>
            {
                HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
                {
                    Method          = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateInvalidGrantTokenResponseMessage()
                });
                await context.AcquireTokenSilentAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserIdentifier("unique_id", UserIdentifierType.UniqueId));
            });

            Assert.AreEqual(AdalError.FailedToAcquireTokenSilently, ex.ErrorCode);
            Assert.AreEqual(AdalErrorMessage.FailedToRefreshToken, ex.Message);
            Assert.IsNotNull(ex.InnerException);
            Assert.IsTrue(ex.InnerException is AdalException);
            Assert.AreEqual(((AdalException)ex.InnerException).ErrorCode, "invalid_grant");
        }
        public RefreshTokenCacheItem FindRefreshToken(AuthenticationRequestParameters requestParam)
        {
            lock (lockObject)
            {
                TokenCacheKey key = new TokenCacheKey(null, null, requestParam.ClientKey.ClientId, null, null,
                                                      requestParam.User?.HomeObjectId,
                                                      requestParam.Policy);
                TokenCacheNotificationArgs args = new TokenCacheNotificationArgs
                {
                    TokenCache = this,
                    ClientId   = _clientId,
                    User       = requestParam.User
                };

                OnBeforeAccess(args);
                IList <RefreshTokenCacheItem> refreshTokenCacheItems = TokenCacheAccessor.GetRefreshTokens(key);
                OnAfterAccess(args);
                if (refreshTokenCacheItems.Count == 0)
                {
                    // TODO: no RT returned
                    return(null);
                }

                // User info already provided, if there are multiple items found will throw since we don't what
                // is the one we should use.
                if (refreshTokenCacheItems.Count > 1)
                {
                    throw new MsalException(MsalError.MultipleTokensMatched);
                }

                return(refreshTokenCacheItems[0]);
            }
        }
Exemplo n.º 5
0
        public async Task AcquireTokenWithInvalidResourceTestAsync()
        {
            var           context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache());
            TokenCacheKey key     = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                      TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                      TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId);

            context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "some-access-token", DateTimeOffset.UtcNow)
            };

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateInvalidRequestTokenResponseMessage()
            });

            try
            {
                await context.AcquireTokenSilentAsync("random-resource", TestConstants.DefaultClientId);
            }
            catch (AdalServiceException exc)
            {
                Assert.AreEqual(AdalError.FailedToRefreshToken, exc.ErrorCode);
            }
        }
        public void ConstructorInitCombinations()
        {
            //no policy, user properties
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                  TestConstants.DefaultScope, TestConstants.DefaultClientId,
                                                  TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId);

            this.ValidateTokenCacheKey(key, true);

            //with policy, user properties
            key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                    TestConstants.DefaultScope, TestConstants.DefaultClientId,
                                    TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                                    TestConstants.DefaultPolicy);
            this.ValidateTokenCacheKey(key, false);


            User user = new User();

            user.DisplayableId = TestConstants.DefaultDisplayableId;
            user.UniqueId      = TestConstants.DefaultUniqueId;
            user.HomeObjectId  = TestConstants.DefaultHomeObjectId;

            //no policy, user object
            key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                    TestConstants.DefaultScope, TestConstants.DefaultClientId, user);
            this.ValidateTokenCacheKey(key, true);

            //with policy, user object
            key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                    TestConstants.DefaultScope, TestConstants.DefaultClientId, user,
                                    TestConstants.DefaultPolicy);
            this.ValidateTokenCacheKey(key, false);
        }
        public void TestScopeContains()
        {
            //null scope
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                  null, TestConstants.DefaultClientId,
                                                  TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                                                  TestConstants.DefaultPolicy);

            //null will contain null
            HashSet <string> otherScope = null;

            Assert.IsTrue(key.ScopeContains(otherScope));
            Assert.IsFalse(key.ScopeContains(new HashSet <string>()));

            //put scope value
            key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                    TestConstants.DefaultScope, TestConstants.DefaultClientId,
                                    TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                                    TestConstants.DefaultPolicy);
            Assert.IsTrue(key.ScopeContains(otherScope));
            Assert.IsTrue(key.ScopeContains(new HashSet <string>()));

            otherScope = new HashSet <string>(TestConstants.DefaultScope.ToArray());
            Assert.IsTrue(key.ScopeContains(otherScope));

            // other scope has more
            otherScope.Add("anotherscope");
            Assert.IsFalse(key.ScopeContains(otherScope));
        }
        public void DeleteRefreshToken(TokenCacheKey key)
        {
            CryptographyHelper helper = new CryptographyHelper();
            string             hashed = helper.CreateSha256Hash(key.ToString());

            _refreshTokenContainer.Values.Remove(hashed);
        }
        public async Task AcquireTokenSilentServiceErrorTestAsync()
        {
            Sts           sts   = new AadSts();
            TokenCache    cache = new TokenCache();
            TokenCacheKey key   = new TokenCacheKey(sts.Authority, sts.ValidResource, sts.ValidClientId, TokenSubjectType.User, "unique_id", "*****@*****.**");

            cache.tokenCacheDictionary[key] = new AuthenticationResult("Bearer", "some-access-token",
                                                                       "invalid-refresh-token", DateTimeOffset.UtcNow);

            AuthenticationContext context = new AuthenticationContext(sts.Authority, sts.ValidateAuthority, cache);

            try
            {
                await context.AcquireTokenSilentAsync(sts.ValidResource, sts.ValidClientId, new UserIdentifier("unique_id", UserIdentifierType.UniqueId));

                Verify.Fail("AdalSilentTokenAcquisitionException was expected");
            }
            catch (AdalSilentTokenAcquisitionException ex)
            {
                Verify.AreEqual(AdalError.FailedToAcquireTokenSilently, ex.ErrorCode);
                Verify.AreEqual(AdalErrorMessage.FailedToRefreshToken, ex.Message);
                Verify.IsNotNull(ex.InnerException);
                Verify.IsTrue(ex.InnerException is AdalException);
                Verify.AreEqual(((AdalException)ex.InnerException).ErrorCode, "invalid_grant");
            }
            catch
            {
                Verify.Fail("AdalSilentTokenAcquisitionException was expected");
            }
        }
        public void OBOUserAssertionHashUsernamePassedTest()
        {
            TokenCache    cache         = TokenCacheHelper.CreateCacheWithItems();
            string        someAssertion = "some-assertion-passed-by-developer";
            TokenCacheKey key           = cache.tokenCacheDictionary.Keys.First();

            //update cache entry with hash of an assertion that will not match
            cache.tokenCacheDictionary[key].UserAssertionHash =
                new CryptographyHelper().CreateSha256Hash(someAssertion);

            ConfidentialClientApplication app = new ConfidentialClientApplication(TestConstants.DefaultClientId,
                                                                                  TestConstants.DefaultRedirectUri, new ClientCredential(TestConstants.DefaultClientSecret), new TokenCache());

            app.UserTokenCache = cache;

            //this is a fail safe. No call should go on network
            HttpMessageHandlerFactory.MockHandler = new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage =
                    MockHelpers.CreateInvalidGrantTokenResponseMessage()
            };

            UserAssertion assertion          = new UserAssertion(someAssertion, AssertionType, key.DisplayableId);
            Task <AuthenticationResult> task = app.AcquireTokenOnBehalfOfAsync(key.Scope.AsArray(),
                                                                               assertion, key.Authority, TestConstants.DefaultPolicy);
            AuthenticationResult result = task.Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(key.UniqueId, result.User.UniqueId);
            Assert.AreEqual(key.DisplayableId, result.User.DisplayableId);
            Assert.AreEqual(HashAccessToken,
                            cache.tokenCacheDictionary[key].UserAssertionHash);
        }
        public void TokenCacheKey_GetHashCode_IsNotCurrentCultureDependent()
        {
            var initialCulture = Thread.CurrentThread.CurrentCulture;

            try
            {
                // Setup
                var testSubject = new TokenCacheKey(Authority, Resource, ClientId, SubjectType, UniqueId, "a displayable ID with four types of letter iIİı");

                // Act: en-US as current culture
                Thread.CurrentThread.CurrentCulture = GetEnglishUsCulture();
                var enUsHashCode = testSubject.GetHashCode();

                // Act: tr-TK as current culture
                Thread.CurrentThread.CurrentCulture = GetTurkishCulture();
                var trTkHashCode = testSubject.GetHashCode();

                // Verify
                Assert.AreEqual(enUsHashCode, trTkHashCode, "Expected hash codes to be the same regardless of current thread culture");
            }
            catch (CultureNotFoundException ex)
            {
                Assert.Inconclusive($"The culture {ex.InvalidCultureId} is not available.");
            }
            finally
            {
                // To ensure isolation with other test cases in this assembly,
                // ensure the test exits with the same culture it started with.
                Thread.CurrentThread.CurrentCulture = initialCulture;
            }
        }
        public async Task AutoPromptBehaviorWithTokenInCacheTestAsync()
        {
            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                  TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                  TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId);

            context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token",
                                                              DateTimeOffset.UtcNow + TimeSpan.FromMinutes(100))
            };

            AuthenticationResult result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.Auto)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual("existing-access-token", result.AccessToken);

            // There should be only one cache entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
        public string ToString(TokenCacheKey key)
        {
            var fields = new string[]
            {
                key.Authority,
                key.ClientId,
                key.ExpiresOn.ToString("o", CultureInfo.InvariantCulture),
                key.FamilyName,
                key.GivenName,
                key.IdentityProviderName,
                key.IsMultipleResourceRefreshToken.ToString(),
                key.IsUserIdDisplayable.ToString(),
                key.Resource,
                key.TenantId,
                key.UserId
            };

            // Escape our separator characters. Using ` instead
            // of \ because hey, powershell.
            for (int i = 0; i < fields.Length; ++i)
            {
                if (fields[i] == null)
                {
                    fields[i] = String.Empty;
                }
                fields[i] = fields[i].Replace(escapeString, escapeString + escapeString);
                fields[i] = fields[i].Replace(separatorString, escapeString + separatorString);
            }
            return String.Join(separatorString, fields);
        }
        public async Task AcquireTokenWithValidTokenInCache_ReturnsCachedTokenAsync()
        {
            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                  TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                  TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId);

            context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token",
                                                              DateTimeOffset.UtcNow + TimeSpan.FromMinutes(100))
            };

            var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                                         new UserPasswordCredential(TestConstants.DefaultDisplayableId, TestConstants.DefaultPassword)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual("existing-access-token", result.AccessToken);
            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority);
            Assert.IsNotNull(result.UserInfo);

            // There should be one cached entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
        public void ForcePromptForNeverPromptBehaviorTest()
        {
            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache());

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                  TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                  TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId);

            context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow)
            };

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateInvalidRequestTokenResponseMessage()
            });

            var exc = AssertException.TaskThrows <AdalServiceException>(() =>
                                                                        context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                                                                                  TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.Never)));

            Assert.AreEqual(AdalError.FailedToRefreshToken, exc.ErrorCode);
            // There should be only one cache entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
        internal static void TokenCacheSerializationTest()
        {
            var       context      = new AuthenticationContext("https://login.windows.net/common", false);
            var       tokenCache   = context.TokenCache;
            const int MaxItemCount = 100;
            const int MaxFieldSize = 1024;

            tokenCache.Clear();
            for (int count = 0; count < Rand.Next(1, MaxItemCount); count++)
            {
                TokenCacheKey          key    = GenerateRandomTokenCacheKey();
                AuthenticationResultEx result = GenerateRandomCacheValue(MaxFieldSize, key.UniqueId, key.DisplayableId);
                AddToDictionary(tokenCache, key, result);
            }

            byte[]     serializedCache = tokenCache.Serialize();
            TokenCache tokenCache2     = new TokenCache(serializedCache);

            Assert.AreEqual(tokenCache.Count, tokenCache2.Count);
            foreach (TokenCacheItem item in tokenCache.ReadItems())
            {
                var item2 = tokenCache2.ReadItems().FirstOrDefault(it => it.AccessToken == item.AccessToken);
                Assert.IsNotNull(item2);
                double diff = Math.Abs((item.ExpiresOn - item2.ExpiresOn).TotalSeconds);
                Assert.IsTrue((1.0 - diff) >= 0);
            }

            foreach (var key in tokenCache.tokenCacheDictionary.Keys)
            {
                AuthenticationResultEx result2 = tokenCache2.tokenCacheDictionary[key];
                VerifyAuthenticationResultExsAreEqual(tokenCache.tokenCacheDictionary[key], result2);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Decode cache contents into something we can feed to AuthenticationResult.Deserialize.
        /// WARNING: This will be deprecated eventually by ADAL team and replaced by something supported.
        /// </summary>
        /// <param name="key">The cache key for the entry to decode</param>
        /// <returns>The decoded string to pass to AuthenticationResult.Deserialize</returns>
        private AuthenticationResult DecodeCachedAuthResult(TokenCacheKey key)
        {
            string encoded = tokenCache[key];
            string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));

            return(AuthenticationResult.Deserialize(decoded));
        }
Exemplo n.º 18
0
        public static TokenCacheKey DecodeCacheKey(string cacheKey)
        {
            var elements = new TokenCacheKey();
            IDictionary <TokenCacheKeyElement, string> elementDictionary = Decode(cacheKey);

            elements.Authority            = elementDictionary.ContainsKey(TokenCacheKeyElement.Authority) ? elementDictionary[TokenCacheKeyElement.Authority] : null;
            elements.ClientId             = elementDictionary.ContainsKey(TokenCacheKeyElement.ClientId) ? elementDictionary[TokenCacheKeyElement.ClientId] : null;
            elements.FamilyName           = elementDictionary.ContainsKey(TokenCacheKeyElement.FamilyName) ? elementDictionary[TokenCacheKeyElement.FamilyName] : null;
            elements.GivenName            = elementDictionary.ContainsKey(TokenCacheKeyElement.GivenName) ? elementDictionary[TokenCacheKeyElement.GivenName] : null;
            elements.IdentityProviderName = elementDictionary.ContainsKey(TokenCacheKeyElement.IdentityProviderName) ? elementDictionary[TokenCacheKeyElement.IdentityProviderName] : null;
            elements.Resource             = elementDictionary.ContainsKey(TokenCacheKeyElement.Resource) ? elementDictionary[TokenCacheKeyElement.Resource] : null;
            elements.TenantId             = elementDictionary.ContainsKey(TokenCacheKeyElement.TenantId) ? elementDictionary[TokenCacheKeyElement.TenantId] : null;
            elements.UserId = elementDictionary.ContainsKey(TokenCacheKeyElement.UserId) ? elementDictionary[TokenCacheKeyElement.UserId] : null;

            if (elementDictionary.ContainsKey(TokenCacheKeyElement.ExpiresOn))
            {
                elements.ExpiresOn = DateTimeOffset.Parse(elementDictionary[TokenCacheKeyElement.ExpiresOn]);
            }

            if (elementDictionary.ContainsKey(TokenCacheKeyElement.IsUserIdDisplayable))
            {
                elements.IsUserIdDisplayable = bool.Parse(elementDictionary[TokenCacheKeyElement.IsUserIdDisplayable]);
            }

            if (elementDictionary.ContainsKey(TokenCacheKeyElement.IsMultipleResourceRefreshToken))
            {
                elements.IsMultipleResourceRefreshToken = bool.Parse(elementDictionary[TokenCacheKeyElement.IsMultipleResourceRefreshToken]);
            }

            return(elements);
        }
        internal static void TokenCacheCapacityTest()
        {
            var tokenCache = new TokenCache();

            tokenCache.Clear();

            const int MaxItemCount = 100;

            TokenCacheKey[]          keys   = new TokenCacheKey[MaxItemCount];
            AuthenticationResultEx[] values = new AuthenticationResultEx[MaxItemCount];

            for (int i = 0; i < MaxItemCount; i++)
            {
                keys[i] = GenerateRandomTokenCacheKey();

                values[i] = CreateCacheValue(null, null);
                AddToDictionary(tokenCache, keys[i], values[i]);
            }

            Assert.AreEqual(MaxItemCount, tokenCache.Count);

            for (int i = 0; i < MaxItemCount; i++)
            {
                AuthenticationResultEx cacheValue;
                int index = MaxItemCount - i - 1;
                Assert.IsTrue(tokenCache.tokenCacheDictionary.TryGetValue(keys[index], out cacheValue));
                Assert.AreEqual(values[index], cacheValue);
                RemoveFromDictionary(tokenCache, keys[index]);
                Assert.AreEqual(index, tokenCache.Count);
            }

            tokenCache.Clear();
        }
        public string ToString(TokenCacheKey key)
        {
            var fields = new string[]
            {
                key.Authority,
                key.ClientId,
                key.ExpiresOn.ToString("o", CultureInfo.InvariantCulture),
                key.FamilyName,
                key.GivenName,
                key.IdentityProviderName,
                key.IsMultipleResourceRefreshToken.ToString(),
                key.IsUserIdDisplayable.ToString(),
                key.Resource,
                key.TenantId,
                key.UserId
            };

            // Escape our separator characters. Using ` instead
            // of \ because hey, powershell.
            for (int i = 0; i < fields.Length; ++i)
            {
                if (fields[i] == null)
                {
                    fields[i] = String.Empty;
                }
                fields[i] = fields[i].Replace(escapeString, escapeString + escapeString);
                fields[i] = fields[i].Replace(separatorString, escapeString + separatorString);
            }
            return(String.Join(separatorString, fields));
        }
Exemplo n.º 21
0
        public void SaveRefreshToken(RefreshTokenCacheItem refreshTokenItem)
        {
            TokenCacheKey            key    = refreshTokenItem.GetTokenCacheKey();
            ISharedPreferencesEditor editor = _accessTokenSharedPreference.Edit();

            editor.PutString(key.ToString(), JsonHelper.SerializeToJson(refreshTokenItem));
            editor.Apply();
        }
Exemplo n.º 22
0
 private static void AddToDictionary(TokenCache tokenCache, TokenCacheKey key, AuthenticationResult value)
 {
     tokenCache.OnBeforeAccess(null);
     tokenCache.OnBeforeWrite(null);
     tokenCache.tokenCacheDictionary.Add(key, value);
     tokenCache.HasStateChanged = true;
     tokenCache.OnAfterAccess(null);
 }
Exemplo n.º 23
0
        public static string EncodeCacheKey(TokenCacheKey cacheKey)
        {
            var keyElements = new SortedDictionary <TokenCacheKeyElement, string>();

            keyElements[TokenCacheKeyElement.Authority] = cacheKey.Authority;

            if (!String.IsNullOrEmpty(cacheKey.Resource))
            {
                keyElements[TokenCacheKeyElement.Resource] = cacheKey.Resource;
            }

            if (!String.IsNullOrEmpty(cacheKey.ClientId))
            {
                keyElements[TokenCacheKeyElement.ClientId] = cacheKey.ClientId;
            }

            if (null != cacheKey.ExpiresOn)
            {
                keyElements[TokenCacheKeyElement.ExpiresOn] = cacheKey.ExpiresOn.ToString();
            }

            if (!String.IsNullOrEmpty(cacheKey.FamilyName))
            {
                keyElements[TokenCacheKeyElement.FamilyName] = cacheKey.FamilyName;
            }

            if (!String.IsNullOrEmpty(cacheKey.GivenName))
            {
                keyElements[TokenCacheKeyElement.GivenName] = cacheKey.GivenName;
            }

            if (!String.IsNullOrEmpty(cacheKey.IdentityProviderName))
            {
                keyElements[TokenCacheKeyElement.IdentityProviderName] = cacheKey.IdentityProviderName;
            }

            if (cacheKey.IsMultipleResourceRefreshToken)
            {
                keyElements[TokenCacheKeyElement.IsMultipleResourceRefreshToken] = cacheKey.IsMultipleResourceRefreshToken.ToString();
            }

            if (cacheKey.IsUserIdDisplayable)
            {
                keyElements[TokenCacheKeyElement.IsUserIdDisplayable] = cacheKey.IsUserIdDisplayable.ToString();
            }

            if (!String.IsNullOrEmpty(cacheKey.TenantId))
            {
                keyElements[TokenCacheKeyElement.TenantId] = cacheKey.TenantId;
            }

            if (!String.IsNullOrEmpty(cacheKey.UserId))
            {
                keyElements[TokenCacheKeyElement.UserId] = cacheKey.UserId;
            }

            return(CreateFromKeyElements(keyElements));
        }
Exemplo n.º 24
0
 internal bool Match(TokenCacheKey key)
 {
     return(key != null &&
            (key.Authority == this.Authority && key.ScopeEquals(this.Scope) &&
             key.Equals(key.ClientId, this.ClientId) &&
             key.UniqueId == this.UniqueId &&
             key.Equals(key.DisplayableId, this.DisplayableId) && (key.HomeObjectId == this.HomeObjectId) &&
             key.Equals(key.Policy, this.Policy)));
 }
Exemplo n.º 25
0
        private void DeleteItemFromCache(TokenCacheItem item)
        {
            TokenCacheKey toRemoveKey = this.tokenCacheDictionary.Keys.FirstOrDefault(item.Match);

            if (toRemoveKey != null)
            {
                this.tokenCacheDictionary.Remove(toRemoveKey);
            }
        }
        public void TokenCacheKey_Equals_SameInstancesAreEqual()
        {
            // Setup
            var testSubject = new TokenCacheKey(Authority, Resource, ClientId, SubjectType, UniqueId, DisplayableId);

            // Act
            var result = testSubject.Equals(testSubject);

            // Verify
            Assert.IsTrue(result, "Expected same instance to be considered equal");
        }
        internal static void TokenCacheCrossTenantOperationsTest()
        {
            var tokenCache      = new TokenCache();
            var cacheDictionary = tokenCache.tokenCacheDictionary;

            tokenCache.Clear();

            TokenCacheKey key = new TokenCacheKey("https://localhost/MockSts/", "resource1", "client1",
                                                  TokenSubjectType.User, null, "user1");
            AuthenticationResultEx value = CreateCacheValue(null, "user1");
        }
Exemplo n.º 28
0
        internal void StoreToCache(AuthenticationResultEx resultEx, string authority, string clientId,
                                   string policy, bool restrictToSingleUser, CallState callState)
        {
            lock (lockObject)
            {
                PlatformPlugin.Logger.Verbose(callState, "Storing token in the cache...");

                //single user mode cannot allow more than 1 unique id in the cache including null
                if (restrictToSingleUser &&
                    (resultEx.Result.User == null || string.IsNullOrEmpty(resultEx.Result.User.UniqueId) ||
                     !this.GetUniqueIdsFromCache(clientId).Contains(resultEx.Result.User.UniqueId)))
                {
                    throw new MsalException(MsalError.InvalidCacheOperation,
                                            "Cannot add more than 1 user with a different unique id when RestrictToSingleUser is set to TRUE.");
                }

                this.OnBeforeWrite(new TokenCacheNotificationArgs
                {
                    Scope    = resultEx.Result.Scope,
                    ClientId = clientId,
                    User     = resultEx.Result.User,
                    Policy   = policy
                });

                TokenCacheKey tokenCacheKey = new TokenCacheKey(authority, resultEx.Result.ScopeSet, clientId,
                                                                resultEx.Result.User, policy);
                // First identify all potential tokens.
                List <KeyValuePair <TokenCacheKey, AuthenticationResultEx> > items = this.QueryCache(authority, clientId,
                                                                                                     resultEx.Result.User, policy);
                List <KeyValuePair <TokenCacheKey, AuthenticationResultEx> > itemsToRemove =
                    items.Where(p => p.Key.ScopeIntersects(resultEx.Result.ScopeSet)).ToList();

                if (!itemsToRemove.Any())
                {
                    this.tokenCacheDictionary[tokenCacheKey] = resultEx;
                    PlatformPlugin.Logger.Verbose(callState, "An item was stored in the cache");
                }
                else
                {
                    //remove all intersections
                    PlatformPlugin.Logger.Verbose(callState, "Items to remove - " + itemsToRemove.Count);
                    foreach (var itemToRemove in itemsToRemove)
                    {
                        this.tokenCacheDictionary.Remove(itemToRemove);
                    }

                    this.tokenCacheDictionary[tokenCacheKey] = resultEx;
                    PlatformPlugin.Logger.Verbose(callState, "An item was updated in the cache");
                }

                this.UpdateCachedRefreshTokens(resultEx, authority, clientId, policy);
                this.HasStateChanged = true;
            }
        }
Exemplo n.º 29
0
        public static void CheckPublicGetSets()
        {
            DateTimeOffset now           = DateTimeOffset.UtcNow;
            TokenCacheKey  tokenCacheKey = new TokenCacheKey("Authority", "Resource", "ClientId", TokenSubjectType.User, "UniqueId", "DisplayableId");

            Verify.IsTrue(tokenCacheKey.Authority == "Authority");
            Verify.IsTrue(tokenCacheKey.ClientId == "ClientId");
            Verify.IsTrue(tokenCacheKey.Resource == "Resource");
            Verify.IsTrue(tokenCacheKey.UniqueId == "UniqueId");
            Verify.IsTrue(tokenCacheKey.DisplayableId == "DisplayableId");
            Verify.IsTrue(tokenCacheKey.TokenSubjectType == TokenSubjectType.User);
        }
Exemplo n.º 30
0
        private static bool RemoveFromDictionary(TokenCache tokenCache, TokenCacheKey key)
        {
            bool result;

            tokenCache.OnBeforeAccess(null);
            tokenCache.OnBeforeWrite(null);
            result = tokenCache.tokenCacheDictionary.Remove(key);
            tokenCache.HasStateChanged = true;
            tokenCache.OnAfterAccess(null);

            return(result);
        }
        public static void CheckPublicGetSets()
        {
            TokenCacheKey tokenCacheKey = new TokenCacheKey("Authority", "Resource", "ClientId", TokenSubjectType.User,
                                                            "UniqueId", "DisplayableId");

            Assert.IsTrue(tokenCacheKey.Authority == "Authority");
            Assert.IsTrue(tokenCacheKey.ClientId == "ClientId");
            Assert.IsTrue(tokenCacheKey.Resource == "Resource");
            Assert.IsTrue(tokenCacheKey.UniqueId == "UniqueId");
            Assert.IsTrue(tokenCacheKey.DisplayableId == "DisplayableId");
            Assert.IsTrue(tokenCacheKey.TokenSubjectType == TokenSubjectType.User);
        }
Exemplo n.º 32
0
 /// <summary>
 /// Decode cache contents into something we can feed to AuthenticationResult.Deserialize.
 /// WARNING: This will be deprecated eventually by ADAL team and replaced by something supported.
 /// </summary>
 /// <param name="key">The cache key for the entry to decode</param>
 /// <returns>The decoded string to pass to AuthenticationResult.Deserialize</returns>
 private AuthenticationResult DecodeCachedAuthResult(TokenCacheKey key)
 {
     string encoded = tokenCache[key];
     string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));
     return AuthenticationResult.Deserialize(decoded);
 }