public void AcquireTokenSilentServiceErrorTestAsync() { TokenCache cache = new TokenCache(); TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityCommonTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, "unique_id", "*****@*****.**"); cache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = "something-invalid", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "some-access-token", DateTimeOffset.UtcNow) }; AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, cache); var ex = AssertException.TaskThrows <AdalSilentTokenAcquisitionException>(async() => { HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler() { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateInvalidGrantTokenResponseMessage() }); await context.AcquireTokenSilentAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserIdentifier("unique_id", UserIdentifierType.UniqueId)); }); Assert.AreEqual(AdalError.FailedToAcquireTokenSilently, ex.ErrorCode); Assert.AreEqual(AdalErrorMessage.FailedToRefreshToken, ex.Message); Assert.IsNotNull(ex.InnerException); Assert.IsTrue(ex.InnerException is AdalException); Assert.AreEqual(((AdalException)ex.InnerException).ErrorCode, "invalid_grant"); }
public async Task UnknownUserRealmDiscoveryTestAsync() { AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant); await context.Authenticator.UpdateFromTemplateAsync(null).ConfigureAwait(false); 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\":\"Unknown\",\"cloud_instance_name\":\"login.microsoftonline.com\"}") }, QueryParams = new Dictionary <string, string>() { { "api-version", "1.0" } } }); var ex = AssertException.TaskThrows <AdalException>(() => context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserPasswordCredential(TestConstants.DefaultDisplayableId, TestConstants.DefaultPassword))); Assert.AreEqual(AdalError.UnknownUserType, ex.ErrorCode); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount()); Assert.AreEqual(0, context.TokenCache.Count); }
public void TestDeviceCodeCancel() { using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); const int NumberOfAuthorizationPendingRequestsToInject = 0; var parameters = CreateAuthenticationParametersAndSetupMocks( httpManager, NumberOfAuthorizationPendingRequestsToInject, out HashSet <string> expectedScopes); _cache.ServiceBundle = serviceBundle; var cancellationSource = new CancellationTokenSource(); DeviceCodeResult actualDeviceCodeResult = null; var request = new DeviceCodeRequest( serviceBundle, parameters, ApiEvent.ApiIds.None, async result => { await Task.Delay(200, CancellationToken.None).ConfigureAwait(false); actualDeviceCodeResult = result; }); // We setup the cancel before calling the RunAsync operation since we don't check the cancel // until later and the mock network calls run insanely fast for us to timeout for them. cancellationSource.Cancel(); AssertException.TaskThrows <OperationCanceledException>(() => request.RunAsync(cancellationSource.Token)); } }
public void HttpRequestExceptionIsNotSuppressed() { RunWithMockHttp( (httpManager, serviceBundle, receiver) => { httpManager.AddInstanceDiscoveryMockHandler(); var app = new ConfidentialClientApplication( serviceBundle, MsalTestConstants.ClientId, ClientApplicationBase.DefaultAuthority, MsalTestConstants.RedirectUri, new ClientCredential(MsalTestConstants.ClientSecret), new TokenCache(), new TokenCache()) { ValidateAuthority = false }; // add mock response bigger than 1MB for Http Client httpManager.AddFailingRequest(new InvalidOperationException()); AssertException.TaskThrows <InvalidOperationException>( () => app.AcquireTokenForClientAsync(MsalTestConstants.Scope.ToArray())); }); }
public void ResponseSizeOverLimitTest() { var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var stringChars = new char[1048577]; var random = new Random(); for (int i = 0; i < stringChars.Length; i++) { stringChars[i] = chars[random.Next(chars.Length)]; } var finalString = new string(stringChars); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.DefaultAuthorityCommonTenant) { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(finalString) } }); var exc = AssertException.TaskThrows <HttpRequestException>(() => new HttpClientWrapper(TestConstants.DefaultAuthorityCommonTenant, null).GetResponseAsync()); Assert.AreEqual(exc.Message, "Cannot write more bytes to the buffer than the configured maximum buffer size: 1048576."); }
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 void UserRealmDiscoveryFailsTest() { AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetUserRealmEndpoint(TestConstants.DefaultAuthorityCommonTenant) + "/" + TestConstants.DefaultDisplayableId) { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("Bad request received") }, QueryParams = new Dictionary <string, string>() { { "api-version", "1.0" } } }); var ex = AssertException.TaskThrows <AdalException>(() => context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserPasswordCredential(TestConstants.DefaultDisplayableId, TestConstants.DefaultPassword))); Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount()); Assert.AreEqual(0, context.TokenCache.Count); //To be addressed in a later fix //Assert.AreEqual(((AdalException)ex.InnerException.InnerException).ErrorCode, AdalError.UserRealmDiscoveryFailed); }
public void ManagedUsernameNoPasswordAcquireTokenTest() { using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); httpManager.AddInstanceDiscoveryMockHandler(); AddMockResponseforManagedAccounts(httpManager); _cache.ClientId = MsalTestConstants.ClientId; var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId, ClientApplicationBase.DefaultAuthority) { UserTokenCache = _cache }; SecureString str = null; // Call acquire token var result = AssertException.TaskThrows <MsalException>( async() => await app.AcquireTokenByUsernamePasswordAsync( MsalTestConstants.Scope, MsalTestConstants.User.Username, str).ConfigureAwait(false)); // Check error code Assert.AreEqual(MsalError.PasswordRequiredForManagedUserError, result.ErrorCode); // There should be no cached entries. Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount); } }
public void AcquireTokenByIntegratedWindowsAuthTest_ManagedUser() { // Arrange using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); httpManager.AddInstanceDiscoveryMockHandler(); httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityHomeTenant); AddMockHandlerDefaultUserRealmDiscovery_ManagedUser(httpManager); var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId, ClientApplicationBase.DefaultAuthority); // Act var exception = AssertException.TaskThrows <MsalClientException>( async() => await app.AcquireTokenByIntegratedWindowsAuthAsync( MsalTestConstants.Scope, MsalTestConstants.User.Username) .ConfigureAwait(false)); // Assert Assert.AreEqual(MsalError.IntegratedWindowsAuthNotSupportedForManagedUser, exception.ErrorCode); } }
public async Task IntegratedAuthUsingUpn_MexDoesNotReturnAuthEndpointTestAsync() { AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache()); await context.Authenticator.UpdateFromTemplateAsync(null).ConfigureAwait(false); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler() { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"ver\":\"1.0\",\"account_type\":\"federated\",\"domain_name\":\"microsoft.com\"," + "\"federation_protocol\":\"WSTrust\",\"federation_metadata_url\":" + "\"https://msft.sts.microsoft.com/adfs/services/trust/mex\"," + "\"federation_active_auth_url\":\"https://msft.sts.microsoft.com/adfs/services/trust/2005/usernamemixed\"" + ",\"cloud_instance_name\":\"login.microsoftonline.com\"}") }, QueryParams = new Dictionary <string, string>() { { "api-version", "1.0" } } }); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler("https://msft.sts.microsoft.com/adfs/services/trust/mex") { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(File.ReadAllText("TestMex.xml")) } }); // Mex does not return integrated auth endpoint (.../13/windowstransport) HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler("https://msft.sts.microsoft.com/adfs/services/trust/13/windowstransport") { Method = HttpMethod.Post, ResponseMessage = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("Not found") } }); // Call acquire token, endpoint not found var result = AssertException.TaskThrows <Exception>(() => context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserCredential(TestConstants.DefaultDisplayableId))); // Check exception message Assert.AreEqual("Federated service at https://msft.sts.microsoft.com/adfs/services/trust/13/windowstransport returned error: See inner exception for detail.", result.Message); Assert.AreEqual("Response status code does not indicate success: 404 (NotFound).", result.InnerException.Message); // There should be no cached entries. Assert.AreEqual(0, context.TokenCache.Count); // All mocks are consumed Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount()); }
//292916 Ensure AcquireTokenSilent tests exist in ADAL.NET for public clients public void AcquireTokenSilentWithEmptyCacheTest() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache()); AuthenticationResult result; AdalSilentTokenAcquisitionException ex = AssertException.TaskThrows <AdalSilentTokenAcquisitionException>(async() => result = await context.AcquireTokenSilentAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserIdentifier("unique_id", UserIdentifierType.UniqueId)).ConfigureAwait(false)); Assert.AreEqual(ex.ErrorCode, AdalError.FailedToAcquireTokenSilently); Assert.AreEqual(ex.Message, AdalErrorMessage.FailedToAcquireTokenSilently); Assert.IsNull(ex.InnerException); }
public void ManagedUsernamePasswordCommonAuthorityTest() { using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); httpManager.AddInstanceDiscoveryMockHandler(); httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityCommonTenant); // user realm discovery httpManager.AddMockHandler( new MockHttpMessageHandler { 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" } } }); httpManager.AddMockHandler( new MockHttpMessageHandler { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateInvalidRequestTokenResponseMessage() }); _cache.ClientId = MsalTestConstants.ClientId; var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId, ClientApplicationBase.DefaultAuthority) { UserTokenCache = _cache }; // Call acquire token var result = AssertException.TaskThrows <MsalException>( async() => await app.AcquireTokenByUsernamePasswordAsync( MsalTestConstants.Scope, MsalTestConstants.User.Username, _secureString).ConfigureAwait(false)); // Check inner exception Assert.AreEqual(CoreErrorCodes.InvalidRequest, result.ErrorCode); // There should be no cached entries. Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount); } }
public void MexEndpointFailsToResolveTest() { var ui = new MockWebUI { MockResult = new AuthorizationResult( AuthorizationStatus.Success, MsalTestConstants.AuthorityOrganizationsTenant + "?code=some-code") }; using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); httpManager.AddInstanceDiscoveryMockHandler(); httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityOrganizationsTenant); AddMockHandlerDefaultUserRealmDiscovery(httpManager); // MEX httpManager.AddMockHandler( new MockHttpMessageHandler { Url = "https://msft.sts.microsoft.com/adfs/services/trust/mex", Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent( File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("TestMex.xml")) .Replace("<wsp:All>", " ")) } }); _cache.ClientId = MsalTestConstants.ClientId; var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId, ClientApplicationBase.DefaultAuthority) { UserTokenCache = _cache }; // Call acquire token, Mex parser fails var result = AssertException.TaskThrows <MsalException>( async() => await app.AcquireTokenByUsernamePasswordAsync( MsalTestConstants.Scope, MsalTestConstants.User.Username, _secureString).ConfigureAwait(false)); // Check exception message Assert.AreEqual("Parsing WS metadata exchange failed", result.Message); Assert.AreEqual("parsing_ws_metadata_exchange_failed", result.ErrorCode); // There should be no cached entries. Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount); } }
public void WsTrustRequestAcceptedByService() { AuthenticationContext context = new AuthenticationContext("https://login.microsoftonline.com/common", true); AdalServiceException ex = AssertException.TaskThrows <AdalServiceException>(() => context.AcquireTokenAsync("https://graph.windows.net", "unknown-client-F1E93291-6F42-453A-866F-C2F672F283BD", new UserCredential("*****@*****.**"))); Debug.WriteLine($"Error code: {ex.ErrorCode}"); Debug.WriteLine($"Error message: {ex.Message}"); // If the request is not well-formed then the error message returned will be something like // "Federated service at https://msft.sts.microsoft.com/adfs/services/trust/13/windowstransport returned error: ID3035: The request was not valid or is malformed." Assert.IsFalse(ex.Message.Contains("ID3035"), "Not expecting the request to be rejected as invalid"); }
public void FederatedUsernamePasswordCommonAuthorityTest() { var ui = new MockWebUI { MockResult = new AuthorizationResult( AuthorizationStatus.Success, MsalTestConstants.AuthorityCommonTenant + "?code=some-code") }; using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); httpManager.AddInstanceDiscoveryMockHandler(); httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityCommonTenant); AddMockHandlerDefaultUserRealmDiscovery(httpManager); AddMockHandlerMex(httpManager); AddMockHandlerWsTrustUserName(httpManager); // AAD httpManager.AddMockHandler( new MockHttpMessageHandler { Url = "https://login.microsoftonline.com/common/oauth2/v2.0/token", Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateInvalidRequestTokenResponseMessage() }); _cache.ClientId = MsalTestConstants.ClientId; var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId, ClientApplicationBase.DefaultAuthority) { UserTokenCache = _cache }; // Call acquire token var result = AssertException.TaskThrows <MsalException>( async() => await app.AcquireTokenByUsernamePasswordAsync( MsalTestConstants.Scope, MsalTestConstants.User.Username, _secureString).ConfigureAwait(false)); // Check inner exception Assert.AreEqual(CoreErrorCodes.InvalidRequest, result.ErrorCode); // There should be no cached entries. Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount); } }
public async Task UserRealmDiscoveryTest() { AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant); await context.Authenticator.UpdateFromTemplateAsync(null); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler() { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"ver\":\"1.0\",\"account_type\":\"Federated\",\"domain_name\":\"microsoft.com\"," + "\"federation_protocol\":\"WSTrust\",\"federation_metadata_url\":" + "\"https://msft.sts.microsoft.com/adfs/services/trust/mex\"," + "\"federation_active_auth_url\":\"https://msft.sts.microsoft.com/adfs/services/trust/2005/usernamemixed\"" + ",\"cloudinstancename\":\"login.microsoftonline.com\"}") }, QueryParams = new Dictionary <string, string>() { { "api-version", "1.0" } } }); UserRealmDiscoveryResponse userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(context.Authenticator.UserRealmUri, TestConstants.DefaultDisplayableId, null); VerifyUserRealmResponse(userRealmResponse, "Federated"); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler() { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"ver\":\"1.0\",\"account_type\":\"Unknown\",\"cloudinstancename\":\"login.microsoftonline.com\"}") }, QueryParams = new Dictionary <string, string>() { { "api-version", "1.0" } } }); userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(context.Authenticator.UserRealmUri, TestConstants.DefaultDisplayableId, null); VerifyUserRealmResponse(userRealmResponse, "Unknown"); var ex = AssertException.TaskThrows <AdalException>(() => UserRealmDiscoveryResponse.CreateByDiscoveryAsync(context.Authenticator.UserRealmUri, null, null)); Assert.IsNotNull(ex.ErrorCode, AdalError.UnknownUser); }
public async Task MexEndpointFailsToResolveTestAsync() { AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache()); await context.Authenticator.UpdateFromTemplateAsync(null).ConfigureAwait(false); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler() { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"ver\":\"1.0\",\"account_type\":\"federated\",\"domain_name\":\"microsoft.com\"," + "\"federation_protocol\":\"WSTrust\",\"federation_metadata_url\":" + "\"https://msft.sts.microsoft.com/adfs/services/trust/mex\"," + "\"federation_active_auth_url\":\"https://msft.sts.microsoft.com/adfs/services/trust/2005/usernamemixed\"" + ",\"cloud_instance_name\":\"login.microsoftonline.com\"}") }, QueryParams = new Dictionary <string, string>() { { "api-version", "1.0" } } }); // Malformed Mex returned HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler("https://msft.sts.microsoft.com/adfs/services/trust/mex") { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(File.ReadAllText("TestMex.xml").Replace("<wsp:All>", " ")) } }); // Call acquire token, Mex parser fails var result = AssertException.TaskThrows <Exception>(() => context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserCredential(TestConstants.DefaultDisplayableId))); // Check exception message Assert.AreEqual("parsing_ws_metadata_exchange_failed: Parsing WS metadata exchange failed", result.Message); // There should be no cached entries. Assert.AreEqual(0, context.TokenCache.Count); // All mocks are consumed Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount()); }
public void ManagedUsernameIncorrectPasswordAcquireTokenTest() { using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); httpManager.AddInstanceDiscoveryMockHandler(); AddMockResponseforManagedAccounts(httpManager); var str = new SecureString(); str.AppendChar('y'); str.MakeReadOnly(); httpManager.AddMockHandler( new MockHttpMessageHandler { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateInvalidGrantTokenResponseMessage(), PostDataObject = new Dictionary <string, object> { { "grant_type", "password" }, { "username", MsalTestConstants.User.Username }, { "password", _secureString } } }); _cache.ClientId = MsalTestConstants.ClientId; var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId, ClientApplicationBase.DefaultAuthority) { UserTokenCache = _cache }; // Call acquire token var result = AssertException.TaskThrows <MsalException>( async() => await app.AcquireTokenByUsernamePasswordAsync( MsalTestConstants.Scope, MsalTestConstants.User.Username, str).ConfigureAwait(false)); // Check error code Assert.AreEqual(CoreErrorCodes.InvalidGrantError, result.ErrorCode); // There should be no cached entries. Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount); } }
public async Task IntegratedAuthMissingMex_FailsMexParsingTestAsync() { AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache()); await context.Authenticator.UpdateFromTemplateAsync(null); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler() { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"ver\":\"1.0\",\"account_type\":\"federated\",\"domain_name\":\"microsoft.com\"," + "\"federation_protocol\":\"WSTrust\",\"federation_metadata_url\":" + "\"https://msft.sts.microsoft.com/adfs/services/trust/mex\"," + "\"federation_active_auth_url\":\"https://msft.sts.microsoft.com/adfs/services/trust/2005/usernamemixed\"" + ",\"cloud_instance_name\":\"login.microsoftonline.com\"}") }, QueryParams = new Dictionary <string, string>() { { "api-version", "1.0" } } }); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler("https://msft.sts.microsoft.com/adfs/services/trust/mex") { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("Not found") } }); // Call acquire token var result = AssertException.TaskThrows <AdalException>(() => context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserCredential(TestConstants.DefaultDisplayableId))); // Check inner exception Assert.AreEqual("Response status code does not indicate success: 404 (NotFound).", result.InnerException.Message); // There should be no cached entries. Assert.AreEqual(0, context.TokenCache.Count); // All mocks are consumed Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount()); }
internal static async Task MultipleUserAssertionHashTestAsync() { TokenCacheKey key = new TokenCacheKey("https://localhost/MockSts/", "resource1", "client1", TokenSubjectType.Client, null, "user1"); TokenCacheKey key2 = new TokenCacheKey("https://localhost/MockSts/", "resource1", "client1", TokenSubjectType.Client, null, "user2"); AuthenticationResultEx value = CreateCacheValue(null, "user1"); value.UserAssertionHash = "hash1"; AuthenticationResultEx value2 = CreateCacheValue(null, "user2"); value2.UserAssertionHash = "hash2"; TokenCache cache = new TokenCache(); cache.tokenCacheDictionary[key] = value; cache.tokenCacheDictionary[key2] = value2; CacheQueryData data = new CacheQueryData() { AssertionHash = "hash1", Authority = "https://localhost/MockSts/", Resource = "resource1", ClientId = "client1", SubjectType = TokenSubjectType.Client, UniqueId = null, DisplayableId = null }; AuthenticationResultEx resultEx = await cache.LoadFromCacheAsync(data, CallState.Default).ConfigureAwait(false); AreAuthenticationResultExsEqual(value, resultEx); data.AssertionHash = "hash2"; resultEx = await cache.LoadFromCacheAsync(data, CallState.Default).ConfigureAwait(false); AreAuthenticationResultExsEqual(value2, resultEx); data.AssertionHash = null; // Multiple tokens in cache -> error var exc = AssertException.TaskThrows <AdalException>(async() => await cache.LoadFromCacheAsync(data, CallState.Default).ConfigureAwait(false)); Assert.AreEqual(exc.ErrorCode, AdalError.MultipleTokensMatched); }
public void NegativeDeviceCodeTest() { MockHttpMessageHandler mockMessageHandler = new MockHttpMessageHandler(TestConstants.DefaultAuthorityHomeTenant) { Method = HttpMethod.Get, Url = TestConstants.DefaultAuthorityHomeTenant + "oauth2/devicecode", ResponseMessage = MockHelpers.CreateDeviceCodeErrorResponse() }; HttpMessageHandlerFactory.AddMockHandler(mockMessageHandler); TokenCache cache = new TokenCache(); AuthenticationContext ctx = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, cache); DeviceCodeResult dcr; AdalServiceException ex = AssertException.TaskThrows <AdalServiceException>(async() => dcr = await ctx.AcquireDeviceCodeAsync("some-resource", "some-client").ConfigureAwait(false)); Assert.IsTrue(ex.Message.Contains("some error message")); }
public void FederatedUsernameNullPasswordTest() { var ui = new MockWebUI { MockResult = new AuthorizationResult( AuthorizationStatus.Success, MsalTestConstants.AuthorityOrganizationsTenant + "?code=some-code") }; using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); httpManager.AddInstanceDiscoveryMockHandler(); httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityOrganizationsTenant); AddMockHandlerDefaultUserRealmDiscovery(httpManager); AddMockHandlerMex(httpManager); // Mex does not return integrated auth endpoint (.../13/windowstransport) httpManager.AddMockHandlerContentNotFound(HttpMethod.Post, "https://msft.sts.microsoft.com/adfs/services/trust/13/windowstransport"); _cache.ClientId = MsalTestConstants.ClientId; var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId, ClientApplicationBase.DefaultAuthority) { UserTokenCache = _cache }; SecureString str = null; // Call acquire token var result = AssertException.TaskThrows <MsalException>( async() => await app.AcquireTokenByUsernamePasswordAsync( MsalTestConstants.Scope, MsalTestConstants.User.Username, str).ConfigureAwait(false)); // Check inner exception Assert.AreEqual(CoreErrorCodes.ParsingWsTrustResponseFailed, result.ErrorCode); // There should be no cached entries. Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount); } }
public async Task NegativeDeviceCodeTimeoutTestAsync() { MockHttpMessageHandler mockMessageHandler = new MockHttpMessageHandler(TestConstants.DefaultAuthorityHomeTenant) { Method = HttpMethod.Get, Url = TestConstants.DefaultAuthorityHomeTenant + "oauth2/devicecode", ResponseMessage = MockHelpers.CreateSuccessDeviceCodeResponseMessage("1") }; HttpMessageHandlerFactory.AddMockHandler(mockMessageHandler); mockMessageHandler = new MockHttpMessageHandler(TestConstants.DefaultAuthorityHomeTenant) { Method = HttpMethod.Post, Url = TestConstants.DefaultAuthorityHomeTenant + "oauth2/token", ResponseMessage = MockHelpers.CreateFailureResponseMessage("{\"error\":\"authorization_pending\"," + "\"error_description\":\"AADSTS70016: Pending end-user authorization." + "\\r\\nTrace ID: f6c2c73f-a21d-474e-a71f-d8b121a58205\\r\\nCorrelation ID: " + "36fe3e82-442f-4418-b9f4-9f4b9295831d\\r\\nTimestamp: 2015-09-24 19:51:51Z\"," + "\"error_codes\":[70016],\"timestamp\":\"2015-09-24 19:51:51Z\",\"trace_id\":" + "\"f6c2c73f-a21d-474e-a71f-d8b121a58205\",\"correlation_id\":" + "\"36fe3e82-442f-4418-b9f4-9f4b9295831d\"}") }; HttpMessageHandlerFactory.AddMockHandler(mockMessageHandler); mockMessageHandler = new MockHttpMessageHandler(TestConstants.DefaultAuthorityHomeTenant) { Method = HttpMethod.Post, Url = TestConstants.DefaultAuthorityHomeTenant + "oauth2/token", ResponseMessage = MockHelpers.CreateDeviceCodeExpirationErrorResponse() }; HttpMessageHandlerFactory.AddMockHandler(mockMessageHandler); TokenCache cache = new TokenCache(); AuthenticationContext ctx = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, cache); DeviceCodeResult dcr = await ctx.AcquireDeviceCodeAsync("some resource", "some authority").ConfigureAwait(false); Assert.IsNotNull(dcr); AuthenticationResult result; AdalServiceException ex = AssertException.TaskThrows <AdalServiceException>(async() => result = await ctx.AcquireTokenByDeviceCodeAsync(dcr).ConfigureAwait(false)); Assert.IsTrue(ex.Message.Contains("Verification code expired")); }
public void AdalClaimsChallengeExceptionThrownWithAcquireTokenClientCredentialWhenClaimsChallengeRequiredTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache()); var credential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler() { Method = HttpMethod.Post, ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(responseContent) } }); var result = AssertException.TaskThrows <AdalClaimChallengeException>(() => context.AcquireTokenAsync(TestConstants.DefaultResource, credential)); Assert.AreEqual(claims.Replace("\\", ""), result.Claims); }
public void AdalClaimsChallengeExceptionThrownWithAuthCodeWhenClaimsChallengeRequiredTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache()); ClientAssertion clientAssertion = new ClientAssertion(TestConstants.DefaultClientId, "some-assertion"); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityCommonTenant)) { Method = HttpMethod.Post, ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(responseContent) } }); var result = AssertException.TaskThrows <AdalClaimChallengeException>(() => context.AcquireTokenByAuthorizationCodeAsync("some-code", TestConstants.DefaultRedirectUri, clientAssertion, TestConstants.DefaultResource)); Assert.AreEqual(claims.Replace("\\", ""), result.Claims); }
public void MexParsingFailsTest() { var ui = new MockWebUI { MockResult = new AuthorizationResult( AuthorizationStatus.Success, MsalTestConstants.AuthorityOrganizationsTenant + "?code=some-code") }; using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); httpManager.AddInstanceDiscoveryMockHandler(); httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityOrganizationsTenant); AddMockHandlerDefaultUserRealmDiscovery(httpManager); // MEX httpManager.AddMockHandlerContentNotFound(HttpMethod.Get, "https://msft.sts.microsoft.com/adfs/services/trust/mex"); _cache.ClientId = MsalTestConstants.ClientId; var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId, ClientApplicationBase.DefaultAuthority) { UserTokenCache = _cache }; // Call acquire token var result = AssertException.TaskThrows <MsalException>( async() => await app.AcquireTokenByUsernamePasswordAsync( MsalTestConstants.Scope, MsalTestConstants.User.Username, _secureString).ConfigureAwait(false)); // Check inner exception Assert.AreEqual("Response status code does not indicate success: 404 (NotFound).", result.Message); // There should be no cached entries. Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount); } }
public void AdalClaimsChallengeExceptionThrownWithClientAssertionWhenClaimsChallengeRequiredTestAsync() { var certificate = new X509Certificate2("valid_cert.pfx", TestConstants.DefaultPassword); var clientAssertion = new ClientAssertionCertificate(TestConstants.DefaultClientId, certificate); var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache()); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityCommonTenant)) { Method = HttpMethod.Post, ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(responseContent) } }); var result = AssertException.TaskThrows <AdalClaimChallengeException>(() => context.AcquireTokenAsync(TestConstants.DefaultResource, clientAssertion)); Assert.AreEqual(claims.Replace("\\", ""), result.Claims); }
public void InnerExceptionIncludedWithAdalClaimsChallengeExceptionTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache()); var credential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityCommonTenant)) { Method = HttpMethod.Post, ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(responseContent) } }); var result = AssertException.TaskThrows <AdalClaimChallengeException>(() => context.AcquireTokenAsync(TestConstants.DefaultResource, credential)); // Check inner exception Assert.AreEqual("Response status code does not indicate success: 400 (BadRequest).", result.InnerException.Message); Assert.AreEqual(responseContent + ": Unknown error", result.InnerException.InnerException.Message); }
public void AcquireTokenByIntegratedWindowsAuthTest_UnknownUser() { // Arrange using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); httpManager.AddInstanceDiscoveryMockHandler(); httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityHomeTenant); // user realm discovery - unknown user type httpManager.AddMockHandler( new MockHttpMessageHandler { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent( "{\"ver\":\"1.0\"," + "\"account_type\":\"Bogus\"}") } }); var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId, ClientApplicationBase.DefaultAuthority); // Act var exception = AssertException.TaskThrows <MsalClientException>( async() => await app.AcquireTokenByIntegratedWindowsAuthAsync( MsalTestConstants.Scope, MsalTestConstants.User.Username) .ConfigureAwait(false)); // Assert Assert.AreEqual(MsalError.UnknownUserType, exception.ErrorCode); } }
public static async Task TokenCacheKeyTestAsync(IPlatformParameters parameters) { CheckPublicGetSets(); string authority = "https://www.gotJwt.com/"; string clientId = Guid.NewGuid().ToString(); string resource = Guid.NewGuid().ToString(); string tenantId = Guid.NewGuid().ToString(); string uniqueId = Guid.NewGuid().ToString(); string displayableId = Guid.NewGuid().ToString(); Uri redirectUri = new Uri("https://www.GetJwt.com"); var authenticationResult = CreateCacheValue(uniqueId, displayableId); authority = authority + tenantId + "/"; UserCredential credential = new UserCredential(displayableId); AuthenticationContext tempContext = new AuthenticationContext(authority, false); var localCache = tempContext.TokenCache; localCache.Clear(); // @Resource, Credential TokenCacheKey tokenCacheKey = new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, uniqueId, displayableId); AddToDictionary(localCache, tokenCacheKey, authenticationResult); AuthenticationContext acWithLocalCache = new AuthenticationContext(authority, false, localCache); AuthenticationResult authenticationResultFromCache = await acWithLocalCache.AcquireTokenAsync(resource, clientId, credential); AreAuthenticationResultsEqual(authenticationResult.Result, authenticationResultFromCache); // Duplicate throws error authenticationResult.Result.UserInfo.UniqueId = null; AddToDictionary(localCache, new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, null, displayableId), authenticationResult); var adae = AssertException.TaskThrows <AdalException>(() => acWithLocalCache.AcquireTokenAsync(resource, clientId, credential)); Assert.IsTrue(adae.ErrorCode == "multiple_matching_tokens_detected" && adae.Message.Contains("The cache contains multiple tokens satisfying the requirements")); adae = AssertException.TaskThrows <AdalException>(async() => { AuthenticationContext acWithDefaultCache = new AuthenticationContext(authority, false); await acWithDefaultCache.AcquireTokenAsync(resource, clientId, credential); Assert.Fail("Exception expected"); }); Assert.IsTrue(adae.ErrorCode == "multiple_matching_tokens_detected" && adae.Message.Contains("The cache contains multiple tokens satisfying the requirements")); // @resource && @clientId acWithLocalCache = new AuthenticationContext(authority, false, localCache); localCache.Clear(); var cacheValue = CreateCacheValue(uniqueId, displayableId); resource = Guid.NewGuid().ToString(); clientId = Guid.NewGuid().ToString(); TokenCacheKey tempKey = new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, null, null); AddToDictionary(localCache, tempKey, cacheValue); RemoveFromDictionary(localCache, tempKey); Assert.IsFalse(localCache.tokenCacheDictionary.ContainsKey(tempKey)); AddToDictionary(localCache, tempKey, cacheValue); authenticationResultFromCache = await acWithLocalCache.AcquireTokenAsync(resource, clientId, redirectUri, parameters); VerifyAuthenticationResultsAreEqual(cacheValue.Result, authenticationResultFromCache); // @resource && @clientId && userId acWithLocalCache = new AuthenticationContext(authority, false, localCache); localCache.Clear(); resource = Guid.NewGuid().ToString(); clientId = Guid.NewGuid().ToString(); uniqueId = Guid.NewGuid().ToString(); displayableId = Guid.NewGuid().ToString(); cacheValue = CreateCacheValue(uniqueId, displayableId); AddToDictionary(localCache, new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, uniqueId, displayableId), cacheValue); var userId = new UserIdentifier(uniqueId, UserIdentifierType.UniqueId); var userIdUpper = new UserIdentifier(displayableId.ToUpper(), UserIdentifierType.RequiredDisplayableId); authenticationResultFromCache = await acWithLocalCache.AcquireTokenSilentAsync(resource, clientId, userId); VerifyAuthenticationResultsAreEqual(cacheValue.Result, authenticationResultFromCache); authenticationResultFromCache = await acWithLocalCache.AcquireTokenSilentAsync(resource, clientId, userIdUpper); VerifyAuthenticationResultsAreEqual(cacheValue.Result, authenticationResultFromCache); authenticationResultFromCache = await acWithLocalCache.AcquireTokenSilentAsync(resource, clientId); VerifyAuthenticationResultsAreEqual(cacheValue.Result, authenticationResultFromCache); }