Example #1
0
        public void GetAccessTokenExpiryInRangeTest()
        {
            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority              = TestConstants.AuthorityHomeTenant,
                ClientId               = TestConstants.ClientId,
                ScopeSet               = TestConstants.Scope,
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                TokenType              = "Bearer",
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromMinutes(4))
            };

            atItem.AccessToken = atItem.GetAccessTokenItemKey().ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atItem.GetAccessTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(atItem);

            Assert.IsNull(cache.FindAccessToken(new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = TestConstants.Scope,
                User           =
                    new User()
                {
                    DisplayableId = TestConstants.DisplayableId,
                    Identifier    = TestConstants.UserIdentifier
                }
            }));
        }
Example #2
0
        /// <summary>
        /// Only used by dev test apps
        /// </summary>
        /// <param name="accessTokenCacheItem"></param>
        internal void SaveAccesTokenCacheItem(AccessTokenCacheItem accessTokenCacheItem)
        {
            lock (LockObject)
            {
                TokenCacheNotificationArgs args = new TokenCacheNotificationArgs
                {
                    TokenCache = this,
                    ClientId   = ClientId,
                    User       = accessTokenCacheItem.User
                };

                try
                {
                    HasStateChanged = true;
                    OnBeforeAccess(args);
                    OnBeforeWrite(args);

                    TokenCacheAccessor.SaveAccessToken(accessTokenCacheItem.GetAccessTokenItemKey().ToString(),
                                                       JsonHelper.SerializeToJson(accessTokenCacheItem));
                }
                finally
                {
                    OnAfterAccess(args);
                    HasStateChanged = false;
                }
            }
        }
Example #3
0
 internal void AddAccessTokenCacheItem(AccessTokenCacheItem accessTokenCacheItem)
 {
     // this method is called by serialize and does not require
     // delegates because serialize itself is called from delegates
     lock (LockObject)
     {
         TokenCacheAccessor.SaveAccessToken(accessTokenCacheItem.GetAccessTokenItemKey().ToString(),
                                            JsonHelper.SerializeToJson(accessTokenCacheItem));
     }
 }
Example #4
0
        public void GetExpiredAccessTokenTest()
        {
            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            AccessTokenCacheItem item = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                RawClientInfo          = MockHelpers.CreateClientInfo(),
                ScopeSet = TestConstants.Scope
            };

            item.IdToken     = IdToken.Parse(item.RawIdToken);
            item.ClientInfo  = ClientInfo.CreateFromJson(item.RawClientInfo);
            item.AccessToken = item.GetAccessTokenItemKey().ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(item);

            cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(item);

            Assert.IsNull(cache.FindAccessToken(new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = TestConstants.Scope,
                User           =
                    new User()
                {
                    DisplayableId = TestConstants.DisplayableId,
                    Identifier    = TestConstants.UserIdentifier
                }
            }));
        }
Example #5
0
        public static void PopulateCache(TokenCacheAccessor accessor)
        {
            AccessTokenCacheItem item = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn))),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                RawClientInfo          = MockHelpers.CreateClientInfo(),
                Scope    = TestConstants.Scope.AsSingleString(),
                ScopeSet = TestConstants.Scope
            };

            item.IdToken     = IdToken.Parse(item.RawIdToken);
            item.ClientInfo  = ClientInfo.CreateFromJson(item.RawClientInfo);
            item.AccessToken = item.GetAccessTokenItemKey().ToString();
            //add access token
            accessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] = JsonHelper.SerializeToJson(item);

            item = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityGuestTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn))),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId + "more", TestConstants.DisplayableId),
                RawClientInfo          = MockHelpers.CreateClientInfo(),
                Scope    = TestConstants.ScopeForAnotherResource.AsSingleString(),
                ScopeSet = TestConstants.ScopeForAnotherResource
            };
            item.IdToken     = IdToken.Parse(item.RawIdToken);
            item.ClientInfo  = ClientInfo.CreateFromJson(item.RawClientInfo);
            item.AccessToken = item.GetAccessTokenItemKey().ToString();
            //add another access token
            accessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] = JsonHelper.SerializeToJson(item);

            AddRefreshTokenToCache(accessor, TestConstants.Uid, TestConstants.Utid, TestConstants.Name);
        }
Example #6
0
        public void GetAppTokenFromCacheTest()
        {
            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            AccessTokenCacheItem item = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ExpiresOnUnixTimestamp =
                    MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)),
                RawIdToken    = null,
                RawClientInfo = null,
                User          = null,
                Scope         = TestConstants.Scope.AsSingleString(),
                ScopeSet      = TestConstants.Scope
            };

            item.AccessToken = item.GetAccessTokenItemKey().ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(item);

            AccessTokenCacheItem cacheItem = cache.FindAccessToken(new AuthenticationRequestParameters()
            {
                IsClientCredentialRequest = true,
                RequestContext            = new RequestContext(Guid.Empty, null),
                Authority        = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                ClientId         = TestConstants.ClientId,
                ClientCredential = TestConstants.CredentialWithSecret,
                Scope            = TestConstants.Scope
            });

            Assert.IsNotNull(cacheItem);
            Assert.AreEqual(item.GetAccessTokenItemKey().ToString(), cacheItem.GetAccessTokenItemKey().ToString());
        }
Example #7
0
        public void GetIntersectedScopesMatchedAccessTokenTest()
        {
            TokenCache cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };
            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ScopeSet  = TestConstants.Scope,
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId)
            };

            // create key out of access token cache item and then
            // set it as the value of the access token.
            AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();

            atItem.AccessToken = atKey.ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);

            var param = new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = new SortedSet <string>(),
                User           =
                    new User()
                {
                    DisplayableId = TestConstants.DisplayableId,
                    Identifier    = TestConstants.UserIdentifier
                }
            };

            param.Scope.Add(TestConstants.Scope.First());
            param.Scope.Add("non-existant-scopes");
            AccessTokenCacheItem item = cache.FindAccessToken(param);

            //intersected scopes are not returned.
            Assert.IsNull(item);
        }
Example #8
0
        public void GetSubsetScopesMatchedAccessTokenTest()
        {
            TokenCache cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };
            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ScopeSet  = TestConstants.Scope,
                Scope     = TestConstants.Scope.AsSingleString(),
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                RawClientInfo          = MockHelpers.CreateClientInfo(),
            };

            atItem.IdToken    = IdToken.Parse(atItem.RawIdToken);
            atItem.ClientInfo = ClientInfo.CreateFromJson(atItem.RawClientInfo);

            // create key out of access token cache item and then
            // set it as the value of the access token.
            AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();

            atItem.AccessToken = atKey.ToString();

            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);
            var param = new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = new SortedSet <string>(),
                User           = TestConstants.User
            };

            param.Scope.Add("r1/scope1");
            AccessTokenCacheItem item = cache.FindAccessToken(param);

            Assert.IsNotNull(item);
            Assert.AreEqual(atKey.ToString(), item.AccessToken);
        }
Example #9
0
        public void GetAccessTokenMatchedUserAssertionInCacheTest()
        {
            TokenCache cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };
            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ScopeSet  = TestConstants.Scope,
                Scope     = TestConstants.Scope.AsSingleString(),
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId)
            };

            // create key out of access token cache item and then
            // set it as the value of the access token.
            AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();

            atItem.AccessToken       = atKey.ToString();
            atItem.UserAssertionHash = CryptographyHelper.CreateBase64UrlEncodedSha256Hash(atKey.ToString());

            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);
            var param = new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = TestConstants.Scope,
                UserAssertion  = new UserAssertion(atKey.ToString())
            };

            cache.AfterAccess = AfterAccessNoChangeNotification;
            AccessTokenCacheItem item = cache.FindAccessToken(param);

            Assert.IsNotNull(item);
            Assert.AreEqual(atKey.ToString(), item.AccessToken);
        }
Example #10
0
        public void GetAccessTokenUserAssertionMismatchInCacheTest()
        {
            TokenCache cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };
            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ScopeSet  = TestConstants.Scope,
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId)
            };

            // create key out of access token cache item and then
            // set it as the value of the access token.
            AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();

            atItem.AccessToken       = atKey.ToString();
            atItem.UserAssertionHash = CryptographyHelper.CreateBase64UrlEncodedSha256Hash(atKey.ToString());

            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);
            var param = new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = TestConstants.Scope,
                UserAssertion  = new UserAssertion(atItem.UserAssertionHash + "-random")
            };

            AccessTokenCacheItem item = cache.FindAccessToken(param);

            // cache lookup should fail because there was userassertion hash did not match the one
            // stored in token cache item.
            Assert.IsNull(item);
        }
Example #11
0
        internal void DeleteAccessToken(AccessTokenCacheItem accessTokenCacheItem)
        {
            lock (LockObject)
            {
                try
                {
                    TokenCacheNotificationArgs args = new TokenCacheNotificationArgs
                    {
                        TokenCache = this,
                        ClientId   = ClientId,
                        User       = accessTokenCacheItem.User
                    };

                    OnBeforeAccess(args);
                    OnBeforeWrite(args);
                    TokenCacheAccessor.DeleteAccessToken(accessTokenCacheItem.GetAccessTokenItemKey().ToString());
                    OnAfterAccess(args);
                }
                finally
                {
                    HasStateChanged = false;
                }
            }
        }
Example #12
0
        internal AccessTokenCacheItem SaveAccessAndRefreshToken(AuthenticationRequestParameters requestParams,
                                                                TokenResponse response)
        {
            lock (LockObject)
            {
                try
                {
                    // create the access token cache item
                    AccessTokenCacheItem accessTokenCacheItem =
                        new AccessTokenCacheItem(requestParams.TenantUpdatedCanonicalAuthority, requestParams.ClientId,
                                                 response)
                    {
                        UserAssertionHash = requestParams.UserAssertion?.AssertionHash
                    };

                    TokenCacheNotificationArgs args = new TokenCacheNotificationArgs
                    {
                        TokenCache = this,
                        ClientId   = ClientId,
                        User       = accessTokenCacheItem.User
                    };

                    HasStateChanged = true;
                    OnBeforeAccess(args);
                    OnBeforeWrite(args);

                    //delete all cache entries with intersecting scopes.
                    //this should not happen but we have this as a safe guard
                    //against multiple matches.
                    requestParams.RequestContext.Logger.Info(
                        "Looking for scopes for the authority in the cache which intersect with " +
                        requestParams.Scope.AsSingleString());
                    IList <AccessTokenCacheItem> accessTokenItemList = new List <AccessTokenCacheItem>();
                    foreach (var accessTokenString in TokenCacheAccessor.GetAllAccessTokensAsString())
                    {
                        AccessTokenCacheItem accessTokenItem =
                            JsonHelper.DeserializeFromJson <AccessTokenCacheItem>(accessTokenString);
                        if (accessTokenItem.ClientId.Equals(ClientId) &&
                            accessTokenItem.Authority.Equals(requestParams.TenantUpdatedCanonicalAuthority) &&
                            accessTokenItem.ScopeSet.ScopeIntersects(accessTokenCacheItem.ScopeSet))
                        {
                            requestParams.RequestContext.Logger.Verbose(
                                "Intersecting scopes found - " + accessTokenItem.Scope);
                            accessTokenItemList.Add(accessTokenItem);
                        }
                    }

                    requestParams.RequestContext.Logger.Info(
                        "Intersecting scope entries count - " + accessTokenItemList.Count);

                    if (!requestParams.IsClientCredentialRequest)
                    {
                        //filter by identifer of the user instead
                        accessTokenItemList =
                            accessTokenItemList.Where(
                                item => item.GetUserIdentifier().Equals(accessTokenCacheItem.GetUserIdentifier()))
                            .ToList();
                        requestParams.RequestContext.Logger.Info(
                            "Matching entries after filtering by user - " + accessTokenItemList.Count);
                    }

                    foreach (var cacheItem in accessTokenItemList)
                    {
                        TokenCacheAccessor.DeleteAccessToken(cacheItem.GetAccessTokenItemKey().ToString(), requestParams.RequestContext);
                    }

                    TokenCacheAccessor.SaveAccessToken(accessTokenCacheItem.GetAccessTokenItemKey().ToString(),
                                                       JsonHelper.SerializeToJson(accessTokenCacheItem), requestParams.RequestContext);

                    // if server returns the refresh token back, save it in the cache.
                    if (response.RefreshToken != null)
                    {
                        // create the refresh token cache item
                        RefreshTokenCacheItem refreshTokenCacheItem = new RefreshTokenCacheItem(
                            requestParams.Authority.Host,
                            requestParams.ClientId,
                            response);
                        requestParams.RequestContext.Logger.Info("Saving RT in cache...");
                        TokenCacheAccessor.SaveRefreshToken(refreshTokenCacheItem.GetRefreshTokenItemKey().ToString(),
                                                            JsonHelper.SerializeToJson(refreshTokenCacheItem), requestParams.RequestContext);
                    }

                    OnAfterAccess(args);
                    return(accessTokenCacheItem);
                }
                finally
                {
                    HasStateChanged = false;
                }
            }
        }
Example #13
0
        public void GetUsersTest()
        {
            PublicClientApplication app   = new PublicClientApplication(TestConstants.ClientId);
            IEnumerable <IUser>     users = app.Users;

            Assert.IsNotNull(users);
            Assert.IsFalse(users.Any());
            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            app.UserTokenCache = cache;
            TokenCacheHelper.PopulateCache(cache.TokenCacheAccessor);
            users = app.Users;
            Assert.IsNotNull(users);
            Assert.AreEqual(1, users.Count());

            AccessTokenCacheItem item = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ExpiresOnUnixTimestamp =
                    MsalHelpers.DateTimeToUnixTimestamp((DateTime.UtcNow + TimeSpan.FromSeconds(3600))),
                RawIdToken    = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                RawClientInfo = MockHelpers.CreateClientInfo(),
                ScopeSet      = TestConstants.Scope
            };

            item.IdToken     = IdToken.Parse(item.RawIdToken);
            item.ClientInfo  = ClientInfo.CreateFromJson(item.RawClientInfo);
            item.AccessToken = item.GetAccessTokenItemKey().ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(item);


            // another cache entry for different uid. user count should be 2.
            RefreshTokenCacheItem rtItem = new RefreshTokenCacheItem()
            {
                Environment      = TestConstants.ProductionEnvironment,
                ClientId         = TestConstants.ClientId,
                RefreshToken     = "someRT",
                RawClientInfo    = MockHelpers.CreateClientInfo(TestConstants.Uid + "more", TestConstants.Utid),
                DisplayableId    = TestConstants.DisplayableId,
                IdentityProvider = TestConstants.IdentityProvider,
                Name             = TestConstants.Name
            };

            rtItem.ClientInfo = ClientInfo.CreateFromJson(rtItem.RawClientInfo);
            cache.TokenCacheAccessor.RefreshTokenCacheDictionary[rtItem.GetRefreshTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(rtItem);
            Assert.AreEqual(2, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
            users = app.Users;
            Assert.IsNotNull(users);
            Assert.AreEqual(2, users.Count());

            // another cache entry for different environment. user count should still be 2. Sovereign cloud user must not be returned
            rtItem = new RefreshTokenCacheItem()
            {
                Environment      = TestConstants.SovereignEnvironment,
                ClientId         = TestConstants.ClientId,
                RefreshToken     = "someRT",
                RawClientInfo    = MockHelpers.CreateClientInfo(TestConstants.Uid + "more1", TestConstants.Utid),
                DisplayableId    = TestConstants.DisplayableId,
                IdentityProvider = TestConstants.IdentityProvider,
                Name             = TestConstants.Name
            };
            rtItem.ClientInfo = ClientInfo.CreateFromJson(rtItem.RawClientInfo);
            cache.TokenCacheAccessor.RefreshTokenCacheDictionary[rtItem.GetRefreshTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(rtItem);
            Assert.AreEqual(3, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
            users = app.Users;
            Assert.IsNotNull(users);
            Assert.AreEqual(2, users.Count());
        }
        public void NoCacheLookup()
        {
            Authority authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false);

            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority              = TestConstants.AuthorityHomeTenant,
                ClientId               = TestConstants.ClientId,
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                RawClientInfo          = MockHelpers.CreateClientInfo(),
                TokenType              = "Bearer",
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromSeconds(3599)),
                ScopeSet               = TestConstants.Scope
            };

            atItem.IdToken    = IdToken.Parse(atItem.RawIdToken);
            atItem.ClientInfo = ClientInfo.CreateFromJson(atItem.RawClientInfo);
            AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();

            atItem.AccessToken = atKey.ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);

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

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant)
            });

            MockHttpMessageHandler mockHandler = new MockHttpMessageHandler();

            mockHandler.Method = HttpMethod.Post;

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

            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authority      = authority,
                ClientId       = TestConstants.ClientId,
                Scope          = TestConstants.Scope,
                TokenCache     = cache,
                RequestContext = new RequestContext(Guid.Empty, null)
            };

            parameters.RedirectUri          = new Uri("some://uri");
            parameters.ExtraQueryParameters = "extra=qp";

            InteractiveRequest request = new InteractiveRequest(parameters,
                                                                TestConstants.ScopeForAnotherResource.ToArray(),
                                                                TestConstants.DisplayableId,
                                                                UIBehavior.SelectAccount, ui);
            Task <AuthenticationResult> task = request.RunAsync();

            task.Wait();
            AuthenticationResult result = task.Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
            Assert.AreEqual(2, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
            Assert.AreEqual(result.AccessToken, "some-access-token");

            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");

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