public void ForcePromptForNeverPromptBehaviorTest() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache()); TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId); context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow) }; HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateInvalidRequestTokenResponseMessage() }); var exc = AssertException.TaskThrows <AdalServiceException>(() => context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.Never))); Assert.AreEqual(AdalError.FailedToRefreshToken, exc.ErrorCode); // There should be only one cache entry. Assert.AreEqual(1, context.TokenCache.Count); }
public async Task AutoPromptBehaviorTestAsync() { MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success, TestConstants.DefaultRedirectUri + "?code=some-code")); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary <string, string>() { { "grant_type", "authorization_code" } } }); var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache()); AuthenticationResult result = await context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.Auto)).ConfigureAwait(false); Assert.IsNotNull(result); Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority); Assert.AreEqual("some-access-token", result.AccessToken); Assert.IsNotNull(result.UserInfo); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); Assert.AreEqual(TestConstants.DefaultUniqueId, result.UserInfo.UniqueId); // There should be one cached entry. Assert.AreEqual(1, context.TokenCache.Count); }
public void AcquireTokenSilentServiceErrorTest() { TokenCache cache = new TokenCache(); TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityCommonTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, "unique_id", "*****@*****.**"); cache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = "something-invalid", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "some-access-token", DateTimeOffset.UtcNow) }; AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, cache); var ex = AssertException.TaskThrows <AdalSilentTokenAcquisitionException>(async() => { HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityCommonTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateInvalidGrantTokenResponseMessage() }); await context.AcquireTokenSilentAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserIdentifier("unique_id", UserIdentifierType.UniqueId)).ConfigureAwait(false); }); Assert.AreEqual(AdalError.FailedToAcquireTokenSilently, ex.ErrorCode); Assert.AreEqual(AdalErrorMessage.FailedToAcquireTokenSilently, ex.Message); Assert.IsNotNull(ex.InnerException); Assert.IsTrue(ex.InnerException is AdalException); Assert.AreEqual(((AdalException)ex.InnerException).ErrorCode, "invalid_grant"); // There should be one cached entry. Assert.AreEqual(1, context.TokenCache.Count); }
//292916 Ensure AcquireTokenSilent tests exist in ADAL.NET for public clients public async Task ExpiredATValidRTInCache_GetNewATRTFromServiceAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache()); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityCommonTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary <string, string>() { { "client_id", TestConstants.DefaultClientId }, { "grant_type", "refresh_token" }, { "refresh_token", "some_rt" } } }); TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityCommonTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId); context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = "some_rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow) }; AuthenticationResult result = await context.AcquireTokenSilentAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserIdentifier(TestConstants.DefaultDisplayableId, UserIdentifierType.RequiredDisplayableId)).ConfigureAwait(false); Assert.IsNotNull(result); }
public async Task ForcePromptForSelectAccountPromptBehaviorTestAsync() { MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success, TestConstants.DefaultRedirectUri + "?code=some-code"), // validate that authorizationUri passed to WebUi contains prompt=select_account query parameter new Dictionary <string, string> { { "prompt", "select_account" } }); var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache()); await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow + TimeSpan.FromMinutes(100)) { UserInfo = new UserInfo() { DisplayableId = TestConstants.DefaultDisplayableId, UniqueId = TestConstants.DefaultUniqueId } }, }, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, new CallState(new Guid())).ConfigureAwait(false); ResetInstanceDiscovery(); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary <string, string> { { "grant_type", "authorization_code" } } }); AuthenticationResult result = await context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.SelectAccount)).ConfigureAwait(false); Assert.IsNotNull(result); Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority); Assert.AreEqual("some-access-token", result.AccessToken); Assert.IsNotNull(result.UserInfo); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); Assert.AreEqual(TestConstants.DefaultUniqueId, result.UserInfo.UniqueId); // There should be only one cache entry. Assert.AreEqual(1, context.TokenCache.Count); }
public async Task SovereignUserWorldWideAuthorityIntegrationTest() { // creating AuthenticationContext with common Authority var authenticationContext = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, false, new TokenCache()); // mock value for authentication returnedUriInput, with cloud_instance_name claim var authReturnedUriInputMock = TestConstants.DefaultRedirectUri + "?code=some-code" + "&" + TokenResponseClaim.CloudInstanceHost + "=" + SovereignAuthorityHost; MockHelpers.ConfigureMockWebUI( new AuthorizationResult(AuthorizationStatus.Success, authReturnedUriInputMock), // validate that authorizationUri passed to WebUi contains instance_aware query parameter new Dictionary <string, string> { { "instance_aware", "true" } }); HttpMessageHandlerFactory.AddMockHandler(MockHelpers.CreateInstanceDiscoveryMockHandler(TestConstants.GetDiscoveryEndpoint(TestConstants.DefaultAuthorityCommonTenant))); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityBlackforestTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultResource), AdditionalRequestValidation = request => { // make sure that Sovereign authority was used for Authorization request Assert.AreEqual(SovereignAuthorityHost, request.RequestUri.Authority); } }); var authenticationResult = await authenticationContext.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, TestConstants.DefaultRedirectUri, _platformParameters, UserIdentifier.AnyUser, "instance_aware=true"); // make sure that tenant specific sovereign Authority returned to the app in AuthenticationResult Assert.AreEqual(_sovereignTenantSpecificAuthority, authenticationResult.Authority); // make sure that AuthenticationContext Authority was updated Assert.AreEqual(_sovereignTenantSpecificAuthority, authenticationContext.Authority); // make sure AT was stored in the cache with tenant specific Sovereign Authority in the key Assert.AreEqual(1, authenticationContext.TokenCache.tokenCacheDictionary.Count); Assert.AreEqual(_sovereignTenantSpecificAuthority, authenticationContext.TokenCache.tokenCacheDictionary.Keys.FirstOrDefault()?.Authority); // all mocks are consumed Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount()); }
public async Task AcquireTokenWithEmptyCache_GetsTokenFromServiceTestAsync() { HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetUserRealmEndpoint(TestConstants.DefaultAuthorityCommonTenant) + "/" + TestConstants.DefaultDisplayableId ) { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"ver\":\"1.0\",\"account_type\":\"Managed\",\"domain_name\":\"id.com\"}") }, QueryParams = new Dictionary <string, string>() { { "api-version", "1.0" } } }); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary <string, string>() { { "grant_type", "password" }, { "username", TestConstants.DefaultDisplayableId }, { "password", TestConstants.DefaultPassword } } }); TokenCache cache = new TokenCache(); var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, cache); var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserPasswordCredential(TestConstants.DefaultDisplayableId, TestConstants.DefaultPassword)).ConfigureAwait(false); Assert.IsNotNull(result); Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority); Assert.AreEqual("some-access-token", result.AccessToken); Assert.IsNotNull(result.UserInfo); Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId); Assert.AreEqual(TestConstants.DefaultUniqueId, result.UserInfo.UniqueId); // All mocks are consumed Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount()); // There should be one cached entry Assert.AreEqual(1, context.TokenCache.Count); }
public async Task AutoPromptBehaviorWithExpiredAccessTokenAndGoodRefreshTokenInCacheTestAsync() { MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success, TestConstants.DefaultRedirectUri + "?code=some-code")); var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache()); await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow) { UserInfo = new UserInfo() { DisplayableId = TestConstants.DefaultDisplayableId, UniqueId = TestConstants.DefaultUniqueId } }, }, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, new CallState(new Guid())).ConfigureAwait(false); ResetInstanceDiscovery(); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary <string, string>() { { "grant_type", "refresh_token" } } }); AuthenticationResult result = await context.AcquireTokenSilentAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserIdentifier(TestConstants.DefaultDisplayableId, UserIdentifierType.RequiredDisplayableId), new PlatformParameters(PromptBehavior.Auto)).ConfigureAwait(false); Assert.IsNotNull(result); Assert.AreEqual("some-access-token", result.AccessToken); // There should be only one cache entry. Assert.AreEqual(1, context.TokenCache.Count); }
public async Task AcquireTokenWithExpiredAccessTokenAndValidRefreshToken_GetsATUsingRTAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache()); await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow) { UserInfo = new UserInfo() { DisplayableId = TestConstants.DefaultDisplayableId, UniqueId = TestConstants.DefaultUniqueId } }, }, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, new CallState(new Guid())).ConfigureAwait(false); ResetInstanceDiscovery(); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary <string, string>() { { "client_id", TestConstants.DefaultClientId }, { "grant_type", "refresh_token" } } }); var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserPasswordCredential(TestConstants.DefaultDisplayableId, TestConstants.DefaultPassword)).ConfigureAwait(false); Assert.IsNotNull(result); Assert.AreEqual("some-access-token", result.AccessToken); Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority); Assert.IsNotNull(result.UserInfo); // Cache entry updated with new access token var entry = await context.TokenCache.LoadFromCacheAsync(new CacheQueryData { Authority = TestConstants.DefaultAuthorityHomeTenant, Resource = TestConstants.DefaultResource, ClientId = TestConstants.DefaultClientId, SubjectType = TokenSubjectType.User, UniqueId = TestConstants.DefaultUniqueId, DisplayableId = TestConstants.DefaultDisplayableId }, new CallState(new Guid())).ConfigureAwait(false); Assert.AreEqual("some-access-token", entry.Result.AccessToken); // There should be one cached entry. Assert.AreEqual(1, context.TokenCache.Count); // All mocks are consumed Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount()); }
public async Task AcquireTokenWithValidAccessTokenInCacheForAnotherUser_GetsTokenFromServiceAsync() { HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler( TestConstants.DefaultAuthorityCommonTenant + "userrealm/[email protected]") { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"ver\":\"1.0\",\"account_type\":\"Managed\",\"domain_name\":\"id.com\"}") }, QueryParams = new Dictionary <string, string>() { { "api-version", "1.0" } } }); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(TestConstants.DefaultUniqueId + "2", "*****@*****.**", TestConstants.DefaultResource), PostData = new Dictionary <string, string>() { { "grant_type", "password" }, { "username", "*****@*****.**" }, { "password", TestConstants.DefaultPassword }, } }); TokenCache cache = new TokenCache(); var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache()); TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId); var setupResult = new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow + +TimeSpan.FromMinutes(100)) }; setupResult.Result.UserInfo = new UserInfo(); setupResult.Result.UserInfo.DisplayableId = TestConstants.DefaultDisplayableId; context.TokenCache.tokenCacheDictionary[key] = setupResult; var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserPasswordCredential("*****@*****.**", TestConstants.DefaultPassword)).ConfigureAwait(false); Assert.IsNotNull(result); Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority); Assert.AreEqual("some-access-token", result.AccessToken); Assert.IsNotNull(result.UserInfo); Assert.AreEqual("*****@*****.**", result.UserInfo.DisplayableId); Assert.AreEqual(TestConstants.DefaultUniqueId + "2", result.UserInfo.UniqueId); // There should be only two cache entrys. Assert.AreEqual(2, context.TokenCache.Count); var keys = context.TokenCache.tokenCacheDictionary.Values.ToList(); var values = context.TokenCache.tokenCacheDictionary.Values.ToList(); Assert.AreNotEqual(keys[0].Result.UserInfo.UniqueId, keys[1].Result.UserInfo.UniqueId); Assert.AreNotEqual(values[0].Result.UserInfo.UniqueId, values[1].Result.UserInfo.UniqueId); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount()); }
public async Task AuthorityNotInInstanceCache_InstanceDiscoverCallMadeTestAsync() { const string content = @"{ ""tenant_discovery_endpoint"":""https://login.microsoftonline.com/tenant/.well-known/openid-configuration"", ""api-version"":""1.1"", ""metadata"":[{ ""preferred_network"":""login.microsoftonline.com"", ""preferred_cache"":""login.windows.net"", ""aliases"":[ ""login.microsoftonline.com"", ""login.windows.net"", ""login.microsoft.com"", ""sts.windows.net""]}]}"; // creating AuthenticationContext with common Authority var authenticationContext = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, false, new TokenCache()); // mock value for authentication returnedUriInput, with cloud_instance_name claim var authReturnedUriInputMock = TestConstants.DefaultRedirectUri + "?code=some-code" + "&" + TokenResponseClaim.CloudInstanceHost + "=" + SovereignAuthorityHost; MockHelpers.ConfigureMockWebUI( new AuthorizationResult(AuthorizationStatus.Success, authReturnedUriInputMock), // validate that authorizationUri passed to WebUi contains instance_aware query parameter new Dictionary <string, string> { { "instance_aware", "true" } }); HttpMessageHandlerFactory.AddMockHandler(MockHelpers.CreateInstanceDiscoveryMockHandler(TestConstants.GetDiscoveryEndpoint(TestConstants.DefaultAuthorityCommonTenant), content)); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetDiscoveryEndpoint(TestConstants.DefaultAuthorityBlackforestTenant)) { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(content) } }); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityBlackforestTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultResource) }); // Assure instance cache is empty Assert.AreEqual(0, InstanceDiscovery.InstanceCache.Count()); await authenticationContext.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, TestConstants.DefaultRedirectUri, _platformParameters, UserIdentifier.AnyUser, "instance_aware=true"); // make sure AT was stored in the cache with tenant specific Sovereign Authority in the key Assert.AreEqual(1, authenticationContext.TokenCache.tokenCacheDictionary.Count); Assert.AreEqual(_sovereignTenantSpecificAuthority, authenticationContext.TokenCache.tokenCacheDictionary.Keys.FirstOrDefault()?.Authority); // DE cloud authority now included in instance cache Assert.AreEqual(5, InstanceDiscovery.InstanceCache.Count()); Assert.AreEqual(true, InstanceDiscovery.InstanceCache.Keys.Contains("login.microsoftonline.de")); Assert.AreEqual(true, InstanceDiscovery.InstanceCache.Keys.Contains("login.windows.net")); Assert.AreEqual(false, InstanceDiscovery.InstanceCache.Keys.Contains("login.partner.microsoftonline.cn")); // all mocks are consumed Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount()); }