public async Task MexParsingFailsTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);

                // MEX
                httpManager.AddMockHandlerContentNotFound(HttpMethod.Get,
                                                          "https://msft.sts.microsoft.com/adfs/services/trust/mex");

                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                                              .WithHttpManager(httpManager)
                                              .BuildConcrete();

                // Call acquire token
                MsalServiceException result = await AssertException.TaskThrowsAsync <MsalServiceException>(
                    async() => await app.AcquireTokenByUsernamePassword(
                        TestConstants.s_scope,
                        TestConstants.s_user.Username,
                        _secureString).ExecuteAsync(CancellationToken.None).ConfigureAwait(false)).ConfigureAwait(false);

                // Check inner exception
                string expectedError = string.Format(CultureInfo.InvariantCulture,
                                                     MsalErrorMessage.HttpRequestUnsuccessful + "See https://aka.ms/msal-net-ropc for more information. ",
                                                     "404", "NotFound");
                Assert.AreEqual(expectedError, result.Message);

                // There should be no cached entries.
                Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
            }
        }
        public async Task FederatedUsernameNullPasswordTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();
                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");

                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                                              .WithHttpManager(httpManager)
                                              .BuildConcrete();

                SecureString str = null;

                // Call acquire token
                MsalClientException result = await AssertException.TaskThrowsAsync <MsalClientException>(
                    async() => await app.AcquireTokenByUsernamePassword(
                        TestConstants.s_scope,
                        TestConstants.s_user.Username,
                        str).ExecuteAsync(CancellationToken.None).ConfigureAwait(false)).ConfigureAwait(false);

                // Check inner exception
                Assert.AreEqual(MsalError.ParsingWsTrustResponseFailed, result.ErrorCode);

                // There should be no cached entries.
                Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
            }
        }
        public async Task MexParsingFailsTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(TestConstants.AuthorityCommonTenant);
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);

                // MEX
                httpManager.AddMockHandlerContentNotFound(HttpMethod.Get,
                                                          "https://msft.sts.microsoft.com/adfs/services/trust/mex");

                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();

                // Call acquire token
                MsalServiceException result = await AssertException.TaskThrowsAsync <MsalServiceException>(
                    async() => await app.AcquireTokenByUsernamePassword(
                        TestConstants.s_scope,
                        TestConstants.s_user.Username,
                        _secureString).ExecuteAsync(CancellationToken.None).ConfigureAwait(false)).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, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
            }
        }
        public async Task WsTrustRequestFailureTestAsync()
        {
            string uri      = "https://some/address/usernamemixed";
            var    endpoint = new WsTrustEndpoint(new Uri(uri), WsTrustVersion.WsTrust13);

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddMockHandlerContentNotFound(HttpMethod.Post, url: uri);

                var requestContext = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null));
                try
                {
                    var message = endpoint.BuildTokenRequestMessageWindowsIntegratedAuth("urn:federation:SomeAudience");

                    WsTrustResponse wstResponse =
                        await serviceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(endpoint, message, requestContext).ConfigureAwait(false);

                    Assert.Fail("We expect an exception to be thrown here");
                }
                catch (MsalException ex)
                {
                    Assert.AreEqual(CoreErrorCodes.FederatedServiceReturnedError, ex.ErrorCode);
                }
            }
        }
        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 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 async Task MexEndpointFailsToResolveTestAsync()
        {
            // TODO: should we move this into a separate test class for WsTrustWebRequestManager?
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddMockHandlerContentNotFound(HttpMethod.Get);

                try
                {
                    await serviceBundle.WsTrustWebRequestManager.GetMexDocumentAsync("http://somehost", _requestContext).ConfigureAwait(false);

                    Assert.Fail("We expect an exception to be thrown here");
                }
                catch (MsalException ex)
                {
                    Assert.AreEqual(CoreErrorCodes.AccessingWsMetadataExchangeFailed, ex.ErrorCode);
                }
            }
        }