public void GetIntersectedScopesMatchedAccessTokenTest() { using (var harness = CreateTestHarness()) { ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false); var atItem = new MsalAccessTokenCacheItem( TestConstants.ProductionPrefNetworkEnvironment, TestConstants.ClientId, TestConstants.s_scope.AsSingleString(), TestConstants.Utid, null, new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(1)), new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)), MockHelpers.CreateClientInfo()); // create key out of access token cache item and then // set it as the value of the access token. string atKey = atItem.GetKey().ToString(); atItem.Secret = atKey; cache.Accessor.SaveAccessToken(atItem); var param = harness.CreateAuthenticationRequestParameters( TestConstants.AuthorityHomeTenant, new SortedSet <string>(), cache, account: new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null)); param.Scope.Add(TestConstants.s_scope.First()); param.Scope.Add("non-existent-scopes"); var item = cache.FindAccessTokenAsync(param).Result; // intersected scopes are not returned. Assert.IsNull(item); } }
public void GetAccessTokenUserAssertionMismatchInCacheTest() { using (var harness = CreateTestHarness()) { ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle); var atItem = new MsalAccessTokenCacheItem( MsalTestConstants.ProductionPrefNetworkEnvironment, MsalTestConstants.ClientId, MsalTestConstants.Scope.AsSingleString(), MsalTestConstants.Utid, null, new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(1)), new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)), MockHelpers.CreateClientInfo()); // create key out of access token cache item and then // set it as the value of the access token. string atKey = atItem.GetKey().ToString(); atItem.Secret = atKey; atItem.UserAssertionHash = harness.ServiceBundle.PlatformProxy.CryptographyManager.CreateBase64UrlEncodedSha256Hash(atKey); cache.Accessor.SaveAccessToken(atItem); var authParams = harness.CreateAuthenticationRequestParameters( MsalTestConstants.AuthorityTestTenant, MsalTestConstants.Scope); authParams.UserAssertion = new UserAssertion(atItem.UserAssertionHash + "-random"); var item = cache.FindAccessTokenAsync(authParams).Result; // cache lookup should fail because there was userassertion hash did not match the one // stored in token cache item. Assert.IsNull(item); } }
public void GetRefreshTokenDifferentEnvironmentTest() { using (var harness = CreateTestHarness()) { ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle); var rtItem = new MsalRefreshTokenCacheItem( TestConstants.SovereignNetworkEnvironment, TestConstants.ClientId, "someRT", MockHelpers.CreateClientInfo()); string rtKey = rtItem.GetKey().ToString(); cache.Accessor.SaveRefreshToken(rtItem); var authParams = harness.CreateAuthenticationRequestParameters( TestConstants.AuthorityTestTenant, TestConstants.s_scope, cache, account: TestConstants.s_user); var rt = cache.FindRefreshTokenAsync(authParams).Result; Assert.IsNull(rt); } }
public void GetRefreshTokenDifferentEnvironmentTest() { using (var harness = new MockHttpAndServiceBundle()) { harness.HttpManager.AddInstanceDiscoveryMockHandler(); ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle); var rtItem = new MsalRefreshTokenCacheItem( MsalTestConstants.SovereignNetworkEnvironment, MsalTestConstants.ClientId, "someRT", MockHelpers.CreateClientInfo()); string rtKey = rtItem.GetKey().ToString(); cache.Accessor.SaveRefreshToken(rtItem); var authParams = harness.CreateAuthenticationRequestParameters( MsalTestConstants.AuthorityTestTenant, MsalTestConstants.Scope, account: MsalTestConstants.User); var rt = cache.FindRefreshTokenAsync(authParams).Result; Assert.IsNull(rt); } }
public void GetAccessTokenMatchedUserAssertionInCacheTest() { using (var harness = CreateTestHarness()) { ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle); var atItem = new MsalAccessTokenCacheItem( TestConstants.ProductionPrefNetworkEnvironment, TestConstants.ClientId, TestConstants.s_scope.AsSingleString(), TestConstants.Utid, null, new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(1)), new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)), MockHelpers.CreateClientInfo()); // create key out of access token cache item and then // set it as the value of the access token. string atKey = atItem.GetKey().ToString(); atItem.Secret = atKey; atItem.UserAssertionHash = harness.ServiceBundle.PlatformProxy.CryptographyManager.CreateBase64UrlEncodedSha256Hash(atKey); cache.Accessor.SaveAccessToken(atItem); var authParams = harness.CreateAuthenticationRequestParameters( TestConstants.AuthorityTestTenant, TestConstants.s_scope); authParams.UserAssertion = new UserAssertion(atKey); ((TokenCache)cache).AfterAccess = AfterAccessNoChangeNotification; var item = cache.FindAccessTokenAsync(authParams).Result; Assert.IsNotNull(item); Assert.AreEqual(atKey, item.Secret); } }
public void TestGetAccounts() { var tokenCacheHelper = new TokenCacheHelper(); using (var httpManager = new MockHttpManager()) { PublicClientApplication app = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId) .WithHttpManager(httpManager) .BuildConcrete(); IEnumerable <IAccount> accounts = app.GetAccountsAsync().Result; Assert.IsNotNull(accounts); Assert.IsFalse(accounts.Any()); tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor); accounts = app.GetAccountsAsync().Result; Assert.IsNotNull(accounts); Assert.AreEqual(1, accounts.Count()); var atItem = new MsalAccessTokenCacheItem( MsalTestConstants.ProductionPrefCacheEnvironment, MsalTestConstants.ClientId, MsalTestConstants.Scope.AsSingleString(), MsalTestConstants.Utid, null, new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3600)), new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(7200)), MockHelpers.CreateClientInfo()); atItem.Secret = atItem.GetKey().ToString(); app.UserTokenCacheInternal.Accessor.SaveAccessToken(atItem); // another cache entry for different uid. user count should be 2. MsalRefreshTokenCacheItem rtItem = new MsalRefreshTokenCacheItem( MsalTestConstants.ProductionPrefCacheEnvironment, MsalTestConstants.ClientId, "someRT", MockHelpers.CreateClientInfo("uId1", "uTId1")); app.UserTokenCacheInternal.Accessor.SaveRefreshToken(rtItem); MsalIdTokenCacheItem idTokenCacheItem = new MsalIdTokenCacheItem( MsalTestConstants.ProductionPrefCacheEnvironment, MsalTestConstants.ClientId, MockHelpers.CreateIdToken(MsalTestConstants.UniqueId, MsalTestConstants.DisplayableId), MockHelpers.CreateClientInfo("uId1", "uTId1"), "uTId1"); app.UserTokenCacheInternal.Accessor.SaveIdToken(idTokenCacheItem); MsalAccountCacheItem accountCacheItem = new MsalAccountCacheItem( MsalTestConstants.ProductionPrefCacheEnvironment, null, MockHelpers.CreateClientInfo("uId1", "uTId1"), null, null, "uTId1", null, null); app.UserTokenCacheInternal.Accessor.SaveAccount(accountCacheItem); Assert.AreEqual(2, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count()); accounts = app.GetAccountsAsync().Result; Assert.IsNotNull(accounts); Assert.AreEqual(2, accounts.Count()); // scoped by env // another cache entry for different environment. user count should still be 2. Sovereign cloud user must not be returned rtItem = new MsalRefreshTokenCacheItem( MsalTestConstants.SovereignNetworkEnvironment, MsalTestConstants.ClientId, "someRT", MockHelpers.CreateClientInfo(MsalTestConstants.Uid + "more1", MsalTestConstants.Utid)); app.UserTokenCacheInternal.Accessor.SaveRefreshToken(rtItem); Assert.AreEqual(3, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count()); accounts = app.GetAccountsAsync().Result; Assert.IsNotNull(accounts); Assert.AreEqual(2, accounts.Count()); } }
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 AcquireTokenNullUserPassedInAndNewUserReturnedFromServiceTest() { cache.ClientId = TestConstants.ClientId; PublicClientApplication app = new PublicClientApplication(TestConstants.ClientId) { UserTokenCache = cache }; MockWebUI ui = new MockWebUI() { MockResult = new AuthorizationResult(AuthorizationStatus.Success, TestConstants.AuthorityHomeTenant + "?code=some-code") }; MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success, app.RedirectUri + "?code=some-code")); //add mock response for tenant endpoint discovery HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler { Method = HttpMethod.Get, ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant) }); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage() }); AuthenticationResult result = app.AcquireTokenAsync(TestConstants.Scope).Result; Assert.IsNotNull(result); Assert.IsNotNull(result.User); Assert.AreEqual(TestConstants.UniqueId, result.UniqueId); Assert.AreEqual(TestConstants.CreateUserIdentifer(), result.User.Identifier); Assert.AreEqual(TestConstants.DisplayableId, result.User.DisplayableId); Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed"); // repeat interactive call and pass in the same user MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success, app.RedirectUri + "?code=some-code")); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(TestConstants.Scope.AsSingleString(), MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId), MockHelpers.CreateClientInfo(TestConstants.Uid, TestConstants.Utid + "more")) }); result = app.AcquireTokenAsync(TestConstants.Scope, (IUser)null, UIBehavior.SelectAccount, null).Result; Assert.IsNotNull(result); Assert.IsNotNull(result.User); Assert.AreEqual(TestConstants.UniqueId, result.UniqueId); Assert.AreEqual(TestConstants.CreateUserIdentifer(TestConstants.Uid, TestConstants.Utid + "more"), result.User.Identifier); Assert.AreEqual(TestConstants.DisplayableId, result.User.DisplayableId); Assert.AreEqual(2, app.Users.Count()); Assert.AreEqual(2, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count); Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed"); }
public void AcquireTokenDifferentUserReturnedFromServiceTest() { cache.ClientId = TestConstants.ClientId; PublicClientApplication app = new PublicClientApplication(TestConstants.ClientId) { UserTokenCache = cache }; MockWebUI ui = new MockWebUI() { MockResult = new AuthorizationResult(AuthorizationStatus.Success, TestConstants.AuthorityHomeTenant + "?code=some-code") }; MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success, app.RedirectUri + "?code=some-code")); //add mock response for tenant endpoint discovery HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler { Method = HttpMethod.Get, ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant) }); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage() }); AuthenticationResult result = app.AcquireTokenAsync(TestConstants.Scope).Result; Assert.IsNotNull(result); Assert.IsNotNull(result.User); Assert.AreEqual(TestConstants.UniqueId, result.UniqueId); Assert.AreEqual(TestConstants.CreateUserIdentifer(), result.User.Identifier); Assert.AreEqual(TestConstants.DisplayableId, result.User.DisplayableId); Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed"); var dict = new Dictionary <string, string>(); dict[OAuth2Parameter.DomainReq] = TestConstants.Utid; dict[OAuth2Parameter.LoginReq] = TestConstants.Uid; // repeat interactive call and pass in the same user MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success, app.RedirectUri + "?code=some-code"), dict); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(TestConstants.Scope.AsSingleString(), MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId), MockHelpers.CreateClientInfo(TestConstants.Uid, TestConstants.Utid + "more")) }); try { result = app.AcquireTokenAsync(TestConstants.Scope, result.User, UIBehavior.SelectAccount, null).Result; Assert.Fail("API should have failed here"); } catch (AggregateException ex) { MsalServiceException exc = (MsalServiceException)ex.InnerException; Assert.IsNotNull(exc); Assert.AreEqual("user_mismatch", exc.ErrorCode); } Assert.IsNotNull(_myReceiver.EventsReceived.Find(anEvent => // Expect finding such an event anEvent[EventBase.EventNameKey].EndsWith("api_event") && anEvent[ApiEvent.ApiIdKey] == "174" && anEvent[ApiEvent.WasSuccessfulKey] == "false" && anEvent[ApiEvent.ApiErrorCodeKey] == "user_mismatch" )); Assert.AreEqual(1, app.Users.Count()); Assert.AreEqual(1, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count); Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed"); }
public void NoCacheLookup() { MyReceiver myReceiver = new MyReceiver(); using (MockHttpAndServiceBundle harness = CreateTestHarness(telemetryCallback: myReceiver.HandleTelemetryEvents)) { TokenCache cache = new TokenCache(harness.ServiceBundle, false); MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem( TestConstants.ProductionPrefNetworkEnvironment, TestConstants.ClientId, TestConstants.s_scope.AsSingleString(), TestConstants.Utid, null, new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)), new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(7200)), MockHelpers.CreateClientInfo()); string atKey = atItem.GetKey().ToString(); atItem.Secret = atKey; ((ITokenCacheInternal)cache).Accessor.SaveAccessToken(atItem); MockWebUI ui = new MockWebUI() { MockResult = AuthorizationResult.FromUri(TestConstants.AuthorityHomeTenant + "?code=some-code") }; MockInstanceDiscoveryAndOpenIdRequest(harness.HttpManager); harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityHomeTenant); AuthenticationRequestParameters parameters = harness.CreateAuthenticationRequestParameters( TestConstants.AuthorityHomeTenant, TestConstants.s_scope, cache, extraQueryParameters: new Dictionary <string, string> { { "extra", "qp" } }); parameters.RedirectUri = new Uri("some://uri"); parameters.LoginHint = TestConstants.DisplayableId; AcquireTokenInteractiveParameters interactiveParameters = new AcquireTokenInteractiveParameters { Prompt = Prompt.SelectAccount, ExtraScopesToConsent = TestConstants.s_scopeForAnotherResource.ToArray(), }; InteractiveRequest request = new InteractiveRequest( harness.ServiceBundle, parameters, interactiveParameters, ui); Task <AuthenticationResult> task = request.RunAsync(CancellationToken.None); task.Wait(); AuthenticationResult result = task.Result; Assert.IsNotNull(result); Assert.AreEqual(1, ((ITokenCacheInternal)cache).Accessor.GetAllRefreshTokens().Count()); Assert.AreEqual(2, ((ITokenCacheInternal)cache).Accessor.GetAllAccessTokens().Count()); Assert.AreEqual(result.AccessToken, "some-access-token"); 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.PromptKey] == "select_account")); Assert.IsNotNull( myReceiver.EventsReceived.Find( anEvent => // Expect finding such an event anEvent[EventBase.EventNameKey].EndsWith("ui_event") && anEvent[UiEvent.AccessDeniedKey] == "false")); } }
private static MockHttpMessageHandler CreateTokenResponseHttpHandler(string authority) { IDictionary <string, string> expectedRequestBody = new Dictionary <string, string>(); expectedRequestBody.Add("scope", TestConstants.ScopeStr); expectedRequestBody.Add("grant_type", "client_credentials"); expectedRequestBody.Add("client_id", TestConstants.ClientId); expectedRequestBody.Add("client_secret", TestConstants.ClientSecret); return(new MockHttpMessageHandler() { ExpectedUrl = $"{authority}/oauth2/v2.0/token", ExpectedMethod = HttpMethod.Post, ExpectedPostData = expectedRequestBody, ResponseMessage = MockHelpers.CreateSuccessfulClientCredentialTokenResponseMessage(MockHelpers.CreateClientInfo(TestConstants.Uid, TestConstants.Utid)) }); }
public void NoCacheLookup() { using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager, _myReceiver); var authority = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityHomeTenant, false); var cache = new TokenCache() { ClientId = MsalTestConstants.ClientId, ServiceBundle = serviceBundle }; var atItem = new MsalAccessTokenCacheItem( MsalTestConstants.ProductionPrefNetworkEnvironment, MsalTestConstants.ClientId, "Bearer", MsalTestConstants.Scope.AsSingleString(), MsalTestConstants.Utid, null, new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)), new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(7200)), MockHelpers.CreateClientInfo()); string atKey = atItem.GetKey().ToString(); atItem.Secret = atKey; cache.TokenCacheAccessor.SaveAccessToken(atItem); var ui = new MockWebUI() { MockResult = new AuthorizationResult( AuthorizationStatus.Success, MsalTestConstants.AuthorityHomeTenant + "?code=some-code") }; MockInstanceDiscoveryAndOpenIdRequest(httpManager); httpManager.AddSuccessTokenResponseMockHandlerForPost(); var parameters = new AuthenticationRequestParameters { Authority = authority, ClientId = MsalTestConstants.ClientId, Scope = MsalTestConstants.Scope, TokenCache = cache, RequestContext = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null)), RedirectUri = new Uri("some://uri"), ExtraQueryParameters = "extra=qp" }; var request = new InteractiveRequest( serviceBundle, parameters, ApiEvent.ApiIds.None, MsalTestConstants.ScopeForAnotherResource.ToArray(), MsalTestConstants.DisplayableId, UIBehavior.SelectAccount, ui); Task <AuthenticationResult> task = request.RunAsync(CancellationToken.None); task.Wait(); var result = task.Result; Assert.IsNotNull(result); Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCount); Assert.AreEqual(2, cache.TokenCacheAccessor.AccessTokenCount); Assert.AreEqual(result.AccessToken, "some-access-token"); 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")); Assert.IsNotNull( _myReceiver.EventsReceived.Find( anEvent => // Expect finding such an event anEvent[EventBase.EventNameKey].EndsWith("ui_event") && anEvent[UiEvent.AccessDeniedKey] == "false")); } }
public async Task NoCacheLookupAsync() { using (MockHttpAndServiceBundle harness = CreateTestHarness()) { TokenCache cache = new TokenCache(harness.ServiceBundle, false); string clientInfo = MockHelpers.CreateClientInfo(); string homeAccountId = ClientInfo.CreateFromJson(clientInfo).ToAccountIdentifier(); MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem( TestConstants.ProductionPrefNetworkEnvironment, TestConstants.ClientId, TestConstants.s_scope.AsSingleString(), TestConstants.Utid, null, new DateTimeOffset(DateTime.UtcNow), new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)), new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(7200)), clientInfo, homeAccountId); string atKey = atItem.GetKey().ToString(); atItem.Secret = atKey; ((ITokenCacheInternal)cache).Accessor.SaveAccessToken(atItem); MockWebUI ui = new MockWebUI() { MockResult = AuthorizationResult.FromUri(TestConstants.AuthorityHomeTenant + "?code=some-code") }; MsalMockHelpers.ConfigureMockWebUI(harness.ServiceBundle, ui); MockInstanceDiscoveryAndOpenIdRequest(harness.HttpManager); harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityHomeTenant); AuthenticationRequestParameters parameters = harness.CreateAuthenticationRequestParameters( TestConstants.AuthorityHomeTenant, TestConstants.s_scope, cache, extraQueryParameters: new Dictionary <string, string> { { "extra", "qp" } }); parameters.RedirectUri = new Uri("some://uri"); parameters.LoginHint = TestConstants.DisplayableId; AcquireTokenInteractiveParameters interactiveParameters = new AcquireTokenInteractiveParameters { Prompt = Prompt.SelectAccount, ExtraScopesToConsent = TestConstants.s_scopeForAnotherResource.ToArray(), }; InteractiveRequest request = new InteractiveRequest( parameters, interactiveParameters); AuthenticationResult result = await request.RunAsync().ConfigureAwait(false); Assert.AreEqual(1, ((ITokenCacheInternal)cache).Accessor.GetAllRefreshTokens().Count()); Assert.AreEqual(2, ((ITokenCacheInternal)cache).Accessor.GetAllAccessTokens().Count()); Assert.AreEqual(result.AccessToken, "some-access-token"); } }
public void SerializeDeserializeCacheTest() { TokenCache cache = new TokenCache() { ClientId = TestConstants.ClientId }; TokenResponse response = new TokenResponse(); response.IdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId); response.ClientInfo = MockHelpers.CreateClientInfo(); response.AccessToken = "access-token"; response.ExpiresIn = 3599; response.CorrelationId = "correlation-id"; response.RefreshToken = "refresh-token"; response.Scope = TestConstants.Scope.AsSingleString(); response.TokenType = "Bearer"; RequestContext requestContext = new RequestContext(Guid.NewGuid(), null); AuthenticationRequestParameters requestParams = new AuthenticationRequestParameters() { RequestContext = requestContext, Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false), ClientId = TestConstants.ClientId, TenantUpdatedCanonicalAuthority = TestConstants.AuthorityHomeTenant }; cache.SaveAccessAndRefreshToken(requestParams, response); byte[] serializedCache = cache.Serialize(); cache.TokenCacheAccessor.AccessTokenCacheDictionary.Clear(); cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Clear(); Assert.AreEqual(0, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count); Assert.AreEqual(0, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count); cache.Deserialize(serializedCache); Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count); Assert.AreEqual(1, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count); serializedCache = cache.Serialize(); cache.Deserialize(serializedCache); //item count should not change because old cache entries should have //been overriden Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count); Assert.AreEqual(1, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count); AccessTokenCacheItem atItem = cache.GetAllAccessTokensForClient(requestContext).First(); Assert.AreEqual(response.AccessToken, atItem.AccessToken); Assert.AreEqual(TestConstants.AuthorityHomeTenant, atItem.Authority); Assert.AreEqual(TestConstants.ClientId, atItem.ClientId); Assert.AreEqual(response.TokenType, atItem.TokenType); Assert.AreEqual(response.Scope, atItem.ScopeSet.AsSingleString()); Assert.AreEqual(response.IdToken, atItem.RawIdToken); RefreshTokenCacheItem rtItem = cache.GetAllRefreshTokensForClient(requestContext).First(); Assert.AreEqual(response.RefreshToken, rtItem.RefreshToken); Assert.AreEqual(TestConstants.ClientId, rtItem.ClientId); Assert.AreEqual(TestConstants.UserIdentifier, rtItem.GetUserIdentifier()); Assert.AreEqual(TestConstants.ProductionEnvironment, rtItem.Environment); }
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")); }