public static TokenCache CreateCacheWithItems()
        {
            TokenCache cache = new TokenCache();
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.ScopeSet = TestConstants.DefaultScope;

            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            key = new TokenCacheKey(TestConstants.DefaultAuthorityGuestTenant,
                TestConstants.ScopeForAnotherResource, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId + "more", TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId + "more",
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.ScopeSet = TestConstants.ScopeForAnotherResource;
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            return cache;
        }
        public void LoadFromCacheExpiredToken()
        {
            TokenCache cache = new TokenCache();
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(), new DateTimeOffset(DateTime.UtcNow));
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            AuthenticationResultEx resultEx = cache.LoadFromCache(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUser,
                TestConstants.DefaultPolicy, null);
            Assert.IsNotNull(resultEx);
            Assert.IsNotNull(resultEx.Result);
            Assert.IsNull(resultEx.Result.Token);
            Assert.AreEqual(resultEx.RefreshToken, "someRT");
        }
        public void StoreToCacheNewUserRestrictToSingleUserTrueTest()
        {
            var tokenCache = new TokenCache();

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            tokenCache.tokenCacheDictionary[key] = ex;
            
            var result = new AuthenticationResult("Bearer", "some-access-token",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)))
            {
                User =
                    new User
                    {
                        UniqueId = TestConstants.DefaultUniqueId+"more",
                        DisplayableId = TestConstants.DefaultDisplayableId
                    },
                ScopeSet = new HashSet<string>(new string[] { "r1/scope5", "r1/scope7" })
            };

            AuthenticationResultEx resultEx = new AuthenticationResultEx
            {
                Result = result,
                RefreshToken = "someRT"
            };
            try
            {
                tokenCache.StoreToCache(resultEx, TestConstants.DefaultAuthorityGuestTenant, TestConstants.DefaultClientId,
                    TestConstants.DefaultPolicy, true, null);
                Assert.Fail("MsalException should be thrown here");
            }
            catch (MsalException me)
            {
                Assert.AreEqual(MsalError.InvalidCacheOperation, me.ErrorCode);
                Assert.AreEqual("Cannot add more than 1 user with a different unique id when RestrictToSingleUser is set to TRUE.", me.Message);
            }
        }
        private AuthenticationResultEx CreateResultExFromCacheResultEx(TokenCacheKey key, AuthenticationResultEx resultEx)
        {
            var newResultEx = new AuthenticationResultEx
            {
                Result = new AuthenticationResult(null, null, DateTimeOffset.MinValue)
                {
                    ScopeSet = new HashSet<string>(resultEx.Result.ScopeSet.ToArray())
                },
                RefreshToken = resultEx.RefreshToken,
            };

            newResultEx.Result.UpdateTenantAndUser(resultEx.Result.TenantId, resultEx.Result.IdToken,
                resultEx.Result.User);

            if (newResultEx.Result.User != null)
            {
                newResultEx.Result.User.Authority = key.Authority;
                newResultEx.Result.User.ClientId = key.ClientId;
                newResultEx.Result.User.TokenCache = this;
            }

            return newResultEx;
        }
Exemple #5
0
        public AuthenticationResultEx GetResultEx()
        {
            AuthenticationResultEx resultEx = null;

            if (!string.IsNullOrEmpty(this.AccessToken) || !string.IsNullOrEmpty(this.IdToken))
            {
                DateTimeOffset accessTokenExpiresOn = DateTime.UtcNow + TimeSpan.FromSeconds(this.ExpiresIn);
                DateTimeOffset idTokenExpiresOn     = DateTime.UtcNow + TimeSpan.FromSeconds(this.IdTokenExpiresIn);

                AuthenticationResult result = null;
                if (!string.IsNullOrEmpty(this.AccessToken))
                {
                    result = new AuthenticationResult(this.TokenType, this.AccessToken, accessTokenExpiresOn);
                }
                else
                {
                    result = new AuthenticationResult(this.TokenType, this.IdToken, idTokenExpiresOn);
                }


                result.FamilyId = FamilyId;
                IdToken idToken = Internal.IdToken.Parse(this.IdToken);
                if (idToken != null)
                {
                    string tenantId = idToken.TenantId;
                    string uniqueId = null;

                    if (!string.IsNullOrWhiteSpace(idToken.ObjectId))
                    {
                        uniqueId = idToken.ObjectId;
                    }
                    else if (!string.IsNullOrWhiteSpace(idToken.Subject))
                    {
                        uniqueId = idToken.Subject;
                    }

                    if (string.IsNullOrWhiteSpace(idToken.HomeObjectId))
                    {
                        idToken.HomeObjectId = uniqueId;
                    }

                    result.UpdateTenantAndUser(tenantId, this.IdToken,
                                               new User
                    {
                        UniqueId         = uniqueId,
                        DisplayableId    = idToken.PreferredUsername,
                        HomeObjectId     = idToken.HomeObjectId,
                        Name             = idToken.Name,
                        IdentityProvider = idToken.Issuer
                    });
                }

                result.ScopeSet = Scope.AsSet();
                resultEx        = new AuthenticationResultEx
                {
                    Result       = result,
                    RefreshToken = this.RefreshToken
                };
            }
            else if (this.Error != null)
            {
                throw new MsalServiceException(this.Error, this.ErrorDescription);
            }
            else
            {
                throw new MsalServiceException(MsalError.Unknown, MsalErrorMessage.Unknown);
            }

            return(resultEx);
        }
        public void NoCacheLookup()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false, Guid.NewGuid());
            TokenCache cache = new TokenCache();
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            IWebUI ui = Substitute.For<IWebUI>();
            AuthorizationResult ar = new AuthorizationResult(AuthorizationStatus.Success,
                TestConstants.DefaultAuthorityHomeTenant + "?code=some-code");
            ui.AcquireAuthorizationAsync(Arg.Any<Uri>(), Arg.Any<Uri>(), Arg.Any<IDictionary<string, string>>(),
                Arg.Any<CallState>())
                .Returns(ar);

            MockHttpMessageHandler mockHandler = new MockHttpMessageHandler();
            mockHandler.Method = HttpMethod.Post;
            mockHandler.QueryParams = new Dictionary<string, string>() {{"p", "some-policy"}};

            mockHandler.ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage();
            HttpMessageHandlerFactory.MockHandler = mockHandler;

            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authenticator = authenticator,
                ClientKey = new ClientKey(TestConstants.DefaultClientId),
                Policy = "some-policy",
                RestrictToSingleUser = TestConstants.DefaultRestrictToSingleUser,
                Scope = TestConstants.DefaultScope.ToArray(),
                TokenCache = cache
            };

            InteractiveRequest request = new InteractiveRequest(parameters,
                TestConstants.ScopeForAnotherResource.ToArray(),
                new Uri("some://uri"), new PlatformParameters(), TestConstants.DefaultDisplayableId,
                UiOptions.SelectAccount, "extra=qp", ui);
            Task<AuthenticationResult> task = request.RunAsync();
            task.Wait();
            AuthenticationResult result = task.Result;
            Assert.IsNotNull(result);
            Assert.AreEqual(2, cache.Count);
            Assert.AreEqual(result.Token, "some-access-token");

            //both cache entry authorities are TestConstants.DefaultAuthorityHomeTenant
            foreach (var item in cache.ReadItems(TestConstants.DefaultClientId))
            {
                Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, item.Authority);
            }
        }
        public AuthenticationResultEx GetResultEx()
        {
            AuthenticationResultEx resultEx = null;
            
            if (!string.IsNullOrEmpty(this.AccessToken) || !string.IsNullOrEmpty(this.IdToken))
            {
                DateTimeOffset accessTokenExpiresOn = DateTime.UtcNow + TimeSpan.FromSeconds(this.ExpiresIn);
                DateTimeOffset idTokenExpiresOn = DateTime.UtcNow + TimeSpan.FromSeconds(this.IdTokenExpiresIn);

                AuthenticationResult result = null;
                if (!string.IsNullOrEmpty(this.AccessToken))
                {
                    result = new AuthenticationResult(this.TokenType, this.AccessToken, accessTokenExpiresOn);
                }
                else
                {
                    result = new AuthenticationResult(this.TokenType, this.IdToken, idTokenExpiresOn);
                }
                

                result.FamilyId = FamilyId;
                IdToken idToken = Internal.IdToken.Parse(this.IdToken);
                if (idToken != null)
                {
                    string tenantId = idToken.TenantId;
                    string uniqueId = null;

                    if (!string.IsNullOrWhiteSpace(idToken.ObjectId))
                    {
                        uniqueId = idToken.ObjectId;
                    }
                    else if (!string.IsNullOrWhiteSpace(idToken.Subject))
                    {
                        uniqueId = idToken.Subject;
                    }

                    if (string.IsNullOrWhiteSpace(idToken.HomeObjectId))
                    {
                        idToken.HomeObjectId = uniqueId;
                    }

                    result.UpdateTenantAndUser(tenantId, this.IdToken,
                        new User
                        {
                            UniqueId = uniqueId,
                            DisplayableId = idToken.PreferredUsername,
                            HomeObjectId = idToken.HomeObjectId,
                            Name = idToken.Name,
                            IdentityProvider = idToken.Issuer
                        });
                }

                result.ScopeSet = Scope.AsSet();
                resultEx = new AuthenticationResultEx
                {
                    Result = result,
                    RefreshToken = this.RefreshToken
                };
            }
            else if (this.Error != null)
            {
                throw new MsalServiceException(this.Error, this.ErrorDescription);
            }
            else
            {
                throw new MsalServiceException(MsalError.Unknown, MsalErrorMessage.Unknown);
            }

            return resultEx;
        }
 private static bool AreAuthenticationResultExsEqual(AuthenticationResultEx resultEx1,
     AuthenticationResultEx resultEx2)
 {
     return AreAuthenticationResultsEqual(resultEx1.Result, resultEx2.Result) &&
            resultEx1.RefreshToken == resultEx2.RefreshToken &&
            resultEx1.IsMultipleScopeRefreshToken == resultEx2.IsMultipleScopeRefreshToken;
 }
        public void LoadFromCacheCrossTenantNullUserToken()
        {
            //this test will result only in a RT and no access token returned.
            TokenCache tokenCache = TokenCacheHelper.CreateCacheWithItems();

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId + "more", TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            tokenCache.tokenCacheDictionary[key] = ex;

            try
            {
                AuthenticationResultEx resultEx =
                    tokenCache.LoadFromCache(TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultScope,
                        TestConstants.DefaultClientId, null, TestConstants.DefaultPolicy, null);
                Assert.Fail("multiple tokens should have been detected");
            }
            catch (MsalException exception)
            {
                Assert.AreEqual("multiple_matching_tokens_detected", exception.ErrorCode);
            }
        }
        public void LoadFromCacheNullUserSingleEntry()
        {
            var tokenCache = new TokenCache();
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            tokenCache.tokenCacheDictionary[key] = ex;

            AuthenticationResultEx resultEx = tokenCache.LoadFromCache(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope,
                TestConstants.DefaultClientId, null,
                TestConstants.DefaultPolicy, null);
            Assert.IsNotNull(resultEx);
            Assert.IsNotNull(resultEx.Result);
            Assert.IsNotNull(resultEx.Result.Token);
        }
        internal async Task<AuthenticationResultEx> RefreshAccessTokenAsync(AuthenticationResultEx result)
        {
            AuthenticationResultEx newResultEx = null;

            if (this.Scope != null)
            {
                PlatformPlugin.Logger.Verbose(this.CallState, "Refreshing access token...");

                try
                {
                    newResultEx = await this.SendTokenRequestByRefreshTokenAsync(result.RefreshToken).ConfigureAwait(false);
                    this.Authenticator.UpdateTenantId(result.Result.TenantId);

                    if (newResultEx.Result.IdToken == null)
                    {
                        // If Id token is not returned by token endpoint when refresh token is redeemed, we should copy tenant and user information from the cached token.
                        newResultEx.Result.UpdateTenantAndUser(result.Result.TenantId, result.Result.IdToken, result.Result.User);
                    }

                }
                catch (MsalException ex)
                {
                    MsalServiceException serviceException = ex as MsalServiceException;
                    if (serviceException != null && serviceException.ErrorCode == "invalid_request")
                    {
                        throw new MsalServiceException(
                            MsalError.FailedToRefreshToken,
                            MsalErrorMessage.FailedToRefreshToken + ". " + serviceException.Message,
                            serviceException.ServiceErrorCodes,
                            serviceException.InnerException);
                    }

                    newResultEx = new AuthenticationResultEx { Exception = ex };
                }
            }

            return newResultEx;
        }
 protected virtual void PostTokenRequest(AuthenticationResultEx result)
 {
     this.Authenticator.UpdateTenantId(result.Result.TenantId);
 }
        private void UpdateCachedRefreshTokens(AuthenticationResultEx result, string authority, string clientId, string policy)
        {
            lock (lockObject)
            {
                if (result.Result.User != null && result.IsMultipleScopeRefreshToken)
                {
                    List<KeyValuePair<TokenCacheKey, AuthenticationResultEx>> mrrtItems =
                        this.QueryCache(authority, clientId, result.Result.User.UniqueId,
                            result.Result.User.DisplayableId, result.Result.User.HomeObjectId, policy)
                            .Where(p => p.Value.IsMultipleScopeRefreshToken)
                            .ToList();

                    foreach (KeyValuePair<TokenCacheKey, AuthenticationResultEx> mrrtItem in mrrtItems)
                    {
                        mrrtItem.Value.RefreshToken = result.RefreshToken;
                    }
                }
            }
        }
        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;
            }
        }
        public void StoreToCacheUniqueScopesTest()
        {
            var tokenCache = new TokenCache();
            tokenCache.AfterAccess = null;
            tokenCache.BeforeAccess = null;
            tokenCache.BeforeWrite = null;
            tokenCache = TokenCacheHelper.CreateCacheWithItems();

            //save result with intersecting scopes
            var result = new AuthenticationResult("Bearer", "some-access-token",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)))
            {
                User =
                    new User
                    {
                        UniqueId = TestConstants.DefaultUniqueId,
                        DisplayableId = TestConstants.DefaultDisplayableId
                    },
                ScopeSet = new HashSet<string>(new string[] { "r1/scope5", "r1/scope7" })
            };

            AuthenticationResultEx resultEx = new AuthenticationResultEx
            {
                Result = result,
                RefreshToken = "someRT"
            };

            tokenCache.StoreToCache(resultEx, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultClientId,
                TestConstants.DefaultPolicy, TestConstants.DefaultRestrictToSingleUser, null);

            Assert.AreEqual(3, tokenCache.Count);
            AuthenticationResultEx resultExOut =
                tokenCache.LoadFromCache(TestConstants.DefaultAuthorityHomeTenant,
                    new HashSet<string>(new string[] {"r1/scope5"}), TestConstants.DefaultClientId,
                    null, TestConstants.DefaultPolicy, null);

            Assert.AreEqual(resultEx.RefreshToken, resultExOut.RefreshToken);
            Assert.AreEqual(resultEx.Result.Token, resultExOut.Result.Token);
            Assert.AreEqual(resultEx.Result.TokenType, resultExOut.Result.TokenType);
            Assert.AreEqual(resultEx.Result.User.UniqueId, resultExOut.Result.User.UniqueId);
            Assert.AreEqual(resultEx.Result.User.DisplayableId, resultExOut.Result.User.DisplayableId);
            Assert.AreEqual(resultEx.Result.User.HomeObjectId, resultExOut.Result.User.HomeObjectId);
        }
 private static void VerifyAuthenticationResultExsAreNotEqual(AuthenticationResultEx resultEx1,
     AuthenticationResultEx resultEx2)
 {
     Assert.IsFalse(AreAuthenticationResultExsEqual(resultEx1, resultEx2));
 }
        public void LoadSingleItemFromCacheNullUserSingleUniqueIdInCacheTest()
        {
            TokenCache cache = new TokenCache();

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            KeyValuePair<TokenCacheKey, AuthenticationResultEx>? item =
                cache.LoadSingleItemFromCache(TestConstants.DefaultAuthorityCommonTenant,
                    TestConstants.DefaultScope, TestConstants.DefaultClientId,
                    null,
                    TestConstants.DefaultPolicy, null);
            Assert.IsNotNull(item);

            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, key.Authority);
            Assert.AreEqual(TestConstants.DefaultScope, key.Scope);
            Assert.AreEqual(TestConstants.DefaultClientId, key.ClientId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, key.UniqueId);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, key.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultHomeObjectId, key.HomeObjectId);
            Assert.AreEqual(TestConstants.DefaultPolicy, key.Policy);
        }
 private static void AddToDictionary(TokenCache tokenCache, TokenCacheKey key, AuthenticationResultEx value)
 {
     tokenCache.OnBeforeAccess(new TokenCacheNotificationArgs {TokenCache = tokenCache});
     tokenCache.OnBeforeWrite(new TokenCacheNotificationArgs {TokenCache = tokenCache});
     tokenCache.tokenCacheDictionary.Add(key, value);
     tokenCache.HasStateChanged = true;
     tokenCache.OnAfterAccess(new TokenCacheNotificationArgs {TokenCache = tokenCache});
 }
        public void LoadSingleItemFromCacheIntersectingScopeDifferentAuthorities()
        {
            TokenCache cache = TokenCacheHelper.CreateCacheWithItems();
            HashSet<string> scope = new HashSet<string>(new[] {"r1/scope1"});

            KeyValuePair<TokenCacheKey, AuthenticationResultEx>? item =
                cache.LoadSingleItemFromCache(TestConstants.DefaultAuthorityHomeTenant,
                    scope, TestConstants.DefaultClientId,
                    TestConstants.DefaultUser,
                    TestConstants.DefaultPolicy, null);
            Assert.IsNotNull(item);
            TokenCacheKey key = item.Value.Key;
            AuthenticationResultEx resultEx = item.Value.Value;

            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, key.Authority);
            Assert.AreEqual(TestConstants.DefaultScope, key.Scope);
            Assert.AreEqual(TestConstants.DefaultClientId, key.ClientId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, key.UniqueId);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, key.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultHomeObjectId, key.HomeObjectId);
            Assert.AreEqual(TestConstants.DefaultPolicy, key.Policy);
            Assert.AreEqual(key.ToString(), resultEx.Result.Token);

            scope.Add("unique-scope");
            item = cache.LoadSingleItemFromCache(TestConstants.DefaultAuthorityHomeTenant,
                scope, TestConstants.DefaultClientId,
                TestConstants.DefaultUser,
                TestConstants.DefaultPolicy, null);

            Assert.IsNotNull(item);
            key = item.Value.Key;
            resultEx = item.Value.Value;

            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, key.Authority);
            Assert.AreEqual(TestConstants.DefaultScope, key.Scope); //default scope contains r1/scope1
            Assert.AreEqual(TestConstants.DefaultClientId, key.ClientId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, key.UniqueId);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, key.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultHomeObjectId, key.HomeObjectId);
            Assert.AreEqual(TestConstants.DefaultPolicy, key.Policy);
            Assert.AreEqual(key.ToString(), resultEx.Result.Token);


            //invoke multiple tokens error
            TokenCacheKey cacheKey = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId + "more", TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[cacheKey] = ex;

            try
            {
                User user = TestConstants.DefaultUser;
                user.DisplayableId = null;

                item = cache.LoadSingleItemFromCache(TestConstants.DefaultAuthorityHomeTenant,
                    TestConstants.DefaultScope, TestConstants.DefaultClientId, user,
                    TestConstants.DefaultPolicy, null);
                Assert.Fail("multiple tokens should have been detected");
            }
            catch (MsalException exception)
            {
                Assert.AreEqual("multiple_matching_tokens_detected", exception.ErrorCode);
            }
        }
        public void ActAsCurrentUserNoSsoHeaderForLoginHintOnlyTest()
        {
            //this test validates that no SSO header is added when developer passes only login hint and UiOption.ActAsCurrentUser
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false, Guid.NewGuid());
            TokenCache cache = new TokenCache();
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            MockWebUI webUi = new MockWebUI();
            webUi.MockResult = new AuthorizationResult(AuthorizationStatus.Success,
                TestConstants.DefaultAuthorityHomeTenant + "?code=some-code");

            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authenticator = authenticator,
                ClientKey = new ClientKey(TestConstants.DefaultClientId),
                Policy = TestConstants.DefaultPolicy,
                RestrictToSingleUser = TestConstants.DefaultRestrictToSingleUser,
                Scope = TestConstants.DefaultScope.ToArray(),
                TokenCache = cache
            };

            InteractiveRequest request = new InteractiveRequest(parameters,
                TestConstants.ScopeForAnotherResource.ToArray(),
                new Uri("some://uri"), new PlatformParameters(),
                ex.Result.User, UiOptions.ActAsCurrentUser, "extra=qp", webUi);
            request.PreRunAsync().Wait();
            request.PreTokenRequest().Wait();
        }
        public void LoadSingleItemFromCacheCrossTenantLookupTest()
        {
            var tokenCache = new TokenCache();

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            tokenCache.tokenCacheDictionary[key] = ex;

            User user = TestConstants.DefaultUser;
            user.DisplayableId = null;
            user.UniqueId = null;

            //cross-tenant works by default. search cache using non-existant authority
            //using root id. Code will find multiple results with the same root id. it can return any.
            KeyValuePair<TokenCacheKey, AuthenticationResultEx>? item =
                tokenCache.LoadSingleItemFromCache(TestConstants.DefaultAuthorityGuestTenant + "non-existant",
                    new HashSet<string>(new[] {"scope1", "random-scope"}),
                    TestConstants.DefaultClientId, user, TestConstants.DefaultPolicy, null);
            Assert.IsNotNull(item);
            key = item.Value.Key;
            AuthenticationResultEx resultEx = item.Value.Value;

            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, key.Authority);
            Assert.AreEqual(TestConstants.DefaultScope, key.Scope);
            Assert.AreEqual(TestConstants.DefaultClientId, key.ClientId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, key.UniqueId);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, key.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultHomeObjectId, key.HomeObjectId);
            Assert.AreEqual(TestConstants.DefaultPolicy, key.Policy);
            Assert.AreEqual(key.ToString(), resultEx.Result.Token);
        }
        public void MapToIdentifierMultipleMatchingEntriesTest()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false,
                Guid.NewGuid());
            TokenCache cache = TokenCacheHelper.CreateCacheWithItems();

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.ScopeForAnotherResource, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3600)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.ScopeSet = TestConstants.DefaultScope;

            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;


            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authenticator = authenticator,
                ClientKey = new ClientKey(TestConstants.DefaultClientId),
                Policy = TestConstants.DefaultPolicy,
                RestrictToSingleUser = TestConstants.DefaultRestrictToSingleUser,
                Scope = new[] { "something" },
                TokenCache = cache
            };

            SilentRequest request = new SilentRequest(parameters, (string) null,
                new PlatformParameters(), false);
            User user = request.MapIdentifierToUser(TestConstants.DefaultUniqueId);
            Assert.IsNotNull(user);
            Assert.AreEqual(TestConstants.DefaultUniqueId, user.UniqueId);
        }
        public void ClearCacheTest()
        {
            TokenCache tokenCache = TokenCacheHelper.CreateCacheWithItems();

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId + "more",
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            tokenCache.tokenCacheDictionary[key] = ex;

            tokenCache.Clear(TestConstants.DefaultClientId);
            Assert.AreEqual(1, tokenCache.Count);
            Assert.AreEqual(key, tokenCache.tokenCacheDictionary.Keys.First());
        }
 protected override void PostTokenRequest(AuthenticationResultEx resultEx)
 {
     base.PostTokenRequest(resultEx);
     //MSAL does not compare the input loginHint to the returned identifier anymore.
 }
        public void StoreToCacheClientCredentialTest()
        {
            TokenCache tokenCache = TokenCacheHelper.CreateCacheWithItems();

            var result = new AuthenticationResult("Bearer", "some-access-token",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)))
            {
                User = null,
                ScopeSet = new HashSet<string>(new string[] { "r1/scope1" })
            };

            AuthenticationResultEx resultEx = new AuthenticationResultEx
            {
                Result = result,
                RefreshToken = null
            };
        }
        public void GetUsersTest()
        {
            PublicClientApplication app = new PublicClientApplication(TestConstants.DefaultClientId);
            IEnumerable<User> users = app.Users;
            Assert.IsNotNull(users);
            Assert.IsFalse(users.Any());
            app.UserTokenCache = TokenCacheHelper.CreateCacheWithItems();
            users = app.Users;
            Assert.IsNotNull(users);
            Assert.AreEqual(1, users.Count());
            foreach (var user in users)
            {
                Assert.AreEqual(TestConstants.DefaultClientId, user.ClientId);
                Assert.IsNotNull(user.TokenCache);
            }

            // another cache entry for different home object id. user count should be 2.
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.ScopeForAnotherResource, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId+"more",
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3600)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.ScopeSet = TestConstants.DefaultScope;

            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            app.UserTokenCache.tokenCacheDictionary[key] = ex;

            users = app.Users;
            Assert.IsNotNull(users);
            Assert.AreEqual(2, users.Count());
            foreach (var user in users)
            {
                Assert.AreEqual(TestConstants.DefaultClientId, user.ClientId);
                Assert.IsNotNull(user.TokenCache);
            }
        }
 protected override void PostTokenRequest(AuthenticationResultEx resultEx)
 {
     base.PostTokenRequest(resultEx);
     this.User = resultEx.Result.User;
 }