Example #1
0
        public void BrokerSilentRequestTest()
        {
            string CanonicalizedAuthority = AuthorityInfo.CanonicalizeAuthorityUri(CoreHelpers.UrlDecode(TestConstants.AuthorityTestTenant));

            using (var harness = CreateBrokerHelper())
            {
                IBroker broker = harness.ServiceBundle.PlatformProxy.CreateBroker(null);
                _brokerSilentAuthStrategy =
                    new SilentBrokerAuthStrategy(
                        new SilentRequest(harness.ServiceBundle, _parameters, _acquireTokenSilentParameters),
                        harness.ServiceBundle,
                        _parameters,
                        _acquireTokenSilentParameters,
                        broker);

                Assert.AreEqual(false, _brokerSilentAuthStrategy.Broker.IsBrokerInstalledAndInvokable());
                AssertException.TaskThrowsAsync <PlatformNotSupportedException>(() => _brokerSilentAuthStrategy.Broker.AcquireTokenSilentAsync(_parameters, _acquireTokenSilentParameters)).ConfigureAwait(false);
            }
        }
Example #2
0
        public async Task MexEndpointFailsToResolveTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(TestConstants.AuthorityOrganizationsTenant);
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);

                // MEX
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedUrl     = "https://msft.sts.microsoft.com/adfs/services/trust/mex",
                    ExpectedMethod  = HttpMethod.Get,
                    ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(
                            File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("TestMex.xml"))
                            .Replace("<wsp:All>", " "))
                    }
                });

                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();

                // Call acquire token, Mex parser fails
                MsalClientException result = await AssertException.TaskThrowsAsync <MsalClientException>(
                    async() => await app.AcquireTokenByUsernamePassword(
                        TestConstants.s_scope,
                        TestConstants.s_user.Username,
                        _secureString).ExecuteAsync(CancellationToken.None).ConfigureAwait(false)).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, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
            }
        }
Example #3
0
        public async Task AcquireTokenByIntegratedWindowsAuthInvalidClientTestAsync()
        {
            IDictionary <string, string> extraQueryParamsAndClaims =
                TestConstants.s_extraQueryParams.ToDictionary(e => e.Key, e => e.Value);

            extraQueryParamsAndClaims.Add(OAuth2Parameter.Claims, TestConstants.Claims);

            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                httpManager.AddMockHandlerForTenantEndpointDiscovery(TestConstants.AuthorityCommonTenant);
                MockHttpMessageHandler realmDiscoveryHandler = AddMockHandlerDefaultUserRealmDiscovery(httpManager);
                AddMockHandlerMex(httpManager);
                AddMockHandlerWsTrustWindowsTransport(httpManager);
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedUrl     = "https://login.microsoftonline.com/common/oauth2/v2.0/token",
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateInvalidClientResponseMessage()
                });

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

                MsalServiceException result = await AssertException.TaskThrowsAsync <MsalServiceException>(
                    async() => await app.AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope)
                    .WithClaims(TestConstants.Claims)
                    .WithUsername(TestConstants.s_user.Username)
                    .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false);

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

                // There should be no cached entries.
                Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
            }
        }
Example #4
0
        public async Task PopWhenBrokerIsNotAvailableTest_Async()
        {
            //MSAL should not fall back to using the browser if the broker is not available when using POP
            // Arrange
            using (var harness = CreateTestHarness())
            {
                harness.HttpManager.AddInstanceDiscoveryMockHandler();

                var mockBroker = Substitute.For <IBroker>();
                mockBroker.IsBrokerInstalledAndInvokable(AuthorityType.Aad).Returns(false);
                mockBroker.IsPopSupported.Returns(true);

                var pca = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                          .WithExperimentalFeatures(true)
                          .WithBrokerPreview()
                          .WithTestBroker(mockBroker)
                          .WithHttpManager(harness.HttpManager)
                          .BuildConcrete();

                pca.ServiceBundle.Config.BrokerCreatorFunc = (x, y, z) => mockBroker;

                pca.ServiceBundle.ConfigureMockWebUI();
                harness.HttpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(
                        "user.read",
                        MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                        MockHelpers.CreateClientInfo(TestConstants.Uid, TestConstants.Utid))
                });

                // Act
                var exception = await AssertException.TaskThrowsAsync <MsalClientException>(async() => { await pca.AcquireTokenInteractive(TestConstants.s_graphScopes)
                                                                                                         .WithProofOfPossession(TestConstants.Nonce, HttpMethod.Get, new Uri(TestConstants.AuthorityCommonTenant))
                                                                                                         .ExecuteAsync()
                                                                                                         .ConfigureAwait(false); }).ConfigureAwait(false);

                Assert.AreEqual(MsalError.BrokerApplicationRequired, exception.ErrorCode);
                Assert.AreEqual(MsalErrorMessage.CannotInvokeBrokerForPop, exception.Message);
            }
        }
        public async Task ROPC_MSA_Async()
        {
            var labResponse = await LabUserHelper.GetMsaUserAsync().ConfigureAwait(false);

            SecureString securePassword = new NetworkCredential("", labResponse.User.GetOrFetchPassword()).SecurePassword;

            var msalPublicClient = PublicClientApplicationBuilder
                                   .Create(labResponse.App.AppId)
                                   .WithAuthority(Authority)
                                   .Build();

            var result = await AssertException.TaskThrowsAsync <MsalClientException>(() =>
                                                                                     msalPublicClient
                                                                                     .AcquireTokenByUsernamePassword(s_scopes, labResponse.User.Upn, securePassword)
                                                                                     .ExecuteAsync(CancellationToken.None))
                         .ConfigureAwait(false);

            Assert.AreEqual(MsalError.RopcDoesNotSupportMsaAccounts, result.ErrorCode);
            Assert.AreEqual(MsalErrorMessage.RopcDoesNotSupportMsaAccounts, result.Message);
        }
Example #6
0
        public async Task HttpRequestExceptionIsNotSuppressedAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                var app = ConfidentialClientApplicationBuilder.Create(MsalTestConstants.ClientId)
                          .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                          .WithRedirectUri(MsalTestConstants.RedirectUri)
                          .WithClientSecret(MsalTestConstants.ClientSecret)
                          .WithHttpManager(httpManager)
                          .BuildConcrete();

                // add mock response bigger than 1MB for Http Client
                httpManager.AddFailingRequest(new InvalidOperationException());

                await AssertException.TaskThrowsAsync <InvalidOperationException>(
                    () => app.AcquireTokenForClient(MsalTestConstants.Scope.ToArray()).ExecuteAsync(CancellationToken.None)).ConfigureAwait(false);
            }
        }
        public async Task AcquireTokenSilent_LoginHint_NoAccountAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId)
                                              .WithAuthority(new Uri(MsalTestConstants.AuthorityTestTenant), true)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();
                _tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);

                var exception = await AssertException.TaskThrowsAsync <MsalUiRequiredException>(() => app.AcquireTokenSilent(
                                                                                                    MsalTestConstants.Scope.ToArray(),
                                                                                                    "*****@*****.**")
                                                                                                .WithAuthority(app.Authority, false)
                                                                                                .ExecuteAsync()).ConfigureAwait(false);

                Assert.AreEqual(MsalError.NoAccountForLoginHint, exception.ErrorCode);
            }
        }
        public async Task AcquireTokenSilent_Account_NoHomeAccountIDAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(TestConstants.AuthorityTestTenant), true)
                                              .WithHttpManager(httpManager)
                                              .BuildConcrete();

                TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);

                var exception = await AssertException.TaskThrowsAsync <MsalUiRequiredException>(() => app.AcquireTokenSilent(
                                                                                                    TestConstants.s_scope.ToArray(),
                                                                                                    new Account(null, null, null))
                                                                                                .ExecuteAsync()).ConfigureAwait(false);

                Assert.AreEqual(MsalError.NoTokensFoundError, exception.ErrorCode);
                Assert.AreEqual(UiRequiredExceptionClassification.AcquireTokenSilentFailed, exception.Classification);
            }
        }
Example #9
0
        public async Task PopWhenBrokerIsNotEnabledForATS_Async()
        {
            // Arrange
            var pca = PublicClientApplicationBuilder
                      .Create(TestConstants.ClientId)
                      .WithExperimentalFeatures()
                      .BuildConcrete();

            // Act

            MsalClientException ex = await AssertException.TaskThrowsAsync <MsalClientException>(async() =>
                                                                                                 await pca.AcquireTokenSilent(TestConstants.s_graphScopes, TestConstants.LocalAccountId)
                                                                                                 .WithProofOfPossession(TestConstants.Nonce, HttpMethod.Get, new Uri(TestConstants.AuthorityCommonTenant))
                                                                                                 .ExecuteAsync()
                                                                                                 .ConfigureAwait(false))
                                     .ConfigureAwait(false);

            Assert.AreEqual(MsalError.BrokerRequiredForPop, ex.ErrorCode);
            Assert.AreEqual(MsalErrorMessage.BrokerRequiredForPop, ex.Message);
        }
        public void BrokerInteractiveRequestTest()
        {
            string CanonicalizedAuthority = AuthorityInfo.CanonicalizeAuthorityUri(CoreHelpers.UrlDecode(MsalTestConstants.AuthorityTestTenant));

            using (var harness = CreateTestHarness())
            {
                // Arrange
                var parameters = harness.CreateAuthenticationRequestParameters(
                    MsalTestConstants.AuthorityTestTenant,
                    null,
                    null,
                    null,
                    MsalTestConstants.ExtraQueryParams);

                // Act
                BrokerFactory            brokerFactory            = new BrokerFactory();
                BrokerInteractiveRequest brokerInteractiveRequest = new BrokerInteractiveRequest(parameters, null, null, null, brokerFactory.Create(harness.ServiceBundle));
                Assert.AreEqual(false, brokerInteractiveRequest.Broker.CanInvokeBroker(null));
                AssertException.TaskThrowsAsync <PlatformNotSupportedException>(() => brokerInteractiveRequest.Broker.AcquireTokenUsingBrokerAsync(new Dictionary <string, string>())).ConfigureAwait(false);
            }
        }
Example #11
0
        private static async Task RunAfterAccessFailureAsync(
            IPublicClientApplication pca,
            Func <Task> operationThatTouchesCache)
        {
            bool beforeAccessCalled = false;
            bool afterAccessCalled  = false;

            pca.UserTokenCache.SetBeforeAccess(args =>
            {
                beforeAccessCalled = true;
                throw new InvalidOperationException();
            });

            pca.UserTokenCache.SetAfterAccess(args => { afterAccessCalled = true; });

            await AssertException.TaskThrowsAsync <InvalidOperationException>(
                operationThatTouchesCache).ConfigureAwait(false);

            Assert.IsTrue(beforeAccessCalled);
            Assert.IsTrue(afterAccessCalled);
        }
        private async Task <PublicClientApplication> SetupAndAcquireOnceAsync(
            MockHttpAndServiceBundle httpManagerAndBundle,
            int httpStatusCode,
            int?retryAfterInSeconds,
            TokenResponseType tokenResponseType)
        {
            Trace.WriteLine("1. Setup test");
            var httpManager = httpManagerAndBundle.HttpManager;

            PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                          .WithHttpManager(httpManager)
                                          .BuildConcrete();

            new TokenCacheHelper().PopulateCache(app.UserTokenCacheInternal.Accessor, expiredAccessTokens: true);

            var tokenResponse = httpManager.AddAllMocks(tokenResponseType);

            UpdateStatusCodeAndHeaders(tokenResponse.ResponseMessage, httpStatusCode, retryAfterInSeconds);

            if (httpStatusCode >= 500 && httpStatusCode < 600 && !retryAfterInSeconds.HasValue)
            {
                var response2 = httpManager.AddTokenResponse(
                    tokenResponseType, s_throttlingHeader);
                UpdateStatusCodeAndHeaders(response2.ResponseMessage, httpStatusCode, retryAfterInSeconds);
            }

            var account = (await app.GetAccountsAsync().ConfigureAwait(false)).Single();

            Trace.WriteLine("2. First failing call ");
            var ex = await AssertException.TaskThrowsAsync <MsalServiceException>(
                () => app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync(),
                allowDerived : true)
                     .ConfigureAwait(false);

            Assert.AreEqual(0, httpManager.QueueSize, "No more requests expected");
            Assert.AreEqual(httpStatusCode, ex.StatusCode);
            Assert.AreEqual(tokenResponseType == TokenResponseType.InvalidGrant, ex is MsalUiRequiredException);

            return(app);
        }
        public async Task AcquireTokenByIntegratedWindowsAuthTest_ManagedUser_DiscoveryFailed_ThrowsExceptionAsync()
        {
            // Arrange
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Get,
                    ResponseMessage = new HttpResponseMessage(HttpStatusCode.NotFound)
                    {
                        Content = new StringContent(
                            "{\"ver\":\"1.0\"," +
                            "\"account_type\":\"Managed\"," +
                            "\"domain_name\":\"some_domain.onmicrosoft.com\"," +
                            "\"cloud_audience_urn\":\"urn:federation:MicrosoftOnline\"," +
                            "\"cloud_instance_name\":\"login.microsoftonline.com\"}")
                    }
                });

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

                // Act
                MsalServiceException exception = await AssertException.TaskThrowsAsync <MsalServiceException>(
                    async() => await app
                    .AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope)
                    .WithUsername(TestConstants.s_user.Username)
                    .ExecuteAsync(CancellationToken.None)
                    .ConfigureAwait(false)).ConfigureAwait(false);

                // Assert
                Assert.AreEqual(MsalError.UserRealmDiscoveryFailed, exception.ErrorCode);
                Assert.AreEqual(HttpStatusCode.NotFound, (HttpStatusCode)exception.StatusCode);
            }
        }
        public async Task AcquireTokenWithFederatedUsernameIncorrectPasswordAsync()
        {
            var labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

            var user = labResponse.User;

            SecureString incorrectSecurePassword = new SecureString();

            incorrectSecurePassword.AppendChar('x');
            incorrectSecurePassword.MakeReadOnly();

            var msalPublicClient = PublicClientApplicationBuilder.Create(labResponse.App.AppId).WithAuthority(_authority).Build();

            var result = await AssertException.TaskThrowsAsync <MsalUiRequiredException>(() =>
                                                                                         msalPublicClient
                                                                                         .AcquireTokenByUsernamePassword(s_scopes, user.Upn, incorrectSecurePassword)
                                                                                         .ExecuteAsync(CancellationToken.None)
                                                                                         )
                         .ConfigureAwait(false);

            Assert.AreEqual(result.ErrorCode, "invalid_grant");
        }
Example #15
0
        public async Task AuthorityValidationTestWithFalseValidateAuthorityAsync()
        {
            LabResponse labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

            LabUser user = labResponse.User;

            IPublicClientApplication pca = PublicClientApplicationBuilder
                                           .Create(labResponse.App.AppId)
                                           .WithAuthority("https://bogus.microsoft.com/common", false)
                                           .WithTestLogging()
                                           .Build();

            Trace.WriteLine("Acquire a token using a not so common authority alias");

            HttpRequestException exception = await AssertException.TaskThrowsAsync <HttpRequestException>(() =>
                                                                                                          pca.AcquireTokenByUsernamePassword(
                                                                                                              s_scopes,
                                                                                                              user.Upn,
                                                                                                              new NetworkCredential("", user.GetOrFetchPassword()).SecurePassword)
                                                                                                          .ExecuteAsync())
                                             .ConfigureAwait(false);
        }
Example #16
0
        public async Task FailingTest_SeleniumFailureAsync()
        {
            var pca = PublicClientApplicationBuilder
                      .Create("1d18b3b0-251b-4714-a02a-9956cec86c2d")
                      .WithRedirectUri(SeleniumWebUI.FindFreeLocalhostRedirectUri())
                      .Build();

            // This should fail after a few seconds
            var seleniumLogic = new SeleniumWebUI((driver) =>
            {
                Trace.WriteLine("Looking for an element that does not exist");
                driver.FindElement(By.Id("i_hope_this_element_does_not_exist"));
            }, TestContext);

            // The exception propagated to the test should be Selenium exception,
            // the test should not wait for the TCP listener to time out
            await AssertException.TaskThrowsAsync <NoSuchElementException>(() => pca
                                                                           .AcquireTokenInteractive(s_scopes)
                                                                           .WithCustomWebUi(seleniumLogic)
                                                                           .ExecuteAsync(CancellationToken.None))
            .ConfigureAwait(false);
        }
Example #17
0
        public async Task RetryAfter_ConfidentialClient_Async()
        {
            using (var httpManagerAndBundle = new MockHttpAndServiceBundle())
            {
                var httpManager = httpManagerAndBundle.HttpManager;
                var app         = ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId)
                                  .WithClientSecret(TestConstants.ClientSecret)
                                  .WithHttpManager(httpManager)
                                  .BuildConcrete();

                var throttlingManager = (httpManagerAndBundle.ServiceBundle.ThrottlingManager as SingletonThrottlingManager);
                var(retryAfterProvider, _, _) = throttlingManager.GetTypedThrottlingProviders();

                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(app.Authority);
                var tokenResponse = httpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage();
                tokenResponse.ResponseMessage.StatusCode = (HttpStatusCode)429;
                const int RetryAfterInSeconds = 10;
                UpdateStatusCodeAndHeaders(tokenResponse.ResponseMessage, 429, RetryAfterInSeconds);

                var ex = await AssertException.TaskThrowsAsync <MsalServiceException>(
                    () => app.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync())
                         .ConfigureAwait(false);

                Assert.AreEqual(429, ex.StatusCode);
                AssertThrottlingCacheEntryCount(throttlingManager, retryAfterEntryCount: 1);

                var ex2 = await AssertException.TaskThrowsAsync <MsalThrottledServiceException>(
                    () => app.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync())
                          .ConfigureAwait(false);

                Assert.AreEqual(429, ex2.StatusCode);
                Assert.AreSame(ex, ex2.OriginalServiceException);

                throttlingManager.SimulateTimePassing(TimeSpan.FromSeconds(RetryAfterInSeconds + 1));
                httpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage();
                await app.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync().ConfigureAwait(false);
            }
        }
Example #18
0
        public async Task SimilarRequests_AreThrottled_HttpStatus_Async()
        {
            using (var httpManagerAndBundle = new MockHttpAndServiceBundle())
            {
                var app = await SetupAndAquireOnceAsync(httpManagerAndBundle, 429, null).ConfigureAwait(false);

                var account           = (await app.GetAccountsAsync().ConfigureAwait(false)).Single();
                var throttlingManager = (httpManagerAndBundle.ServiceBundle.ThrottlingManager as SingletonThrottlingManager);
                AssertThrottlingCacheEntryCount(throttlingManager, httpStatusEntryCount: 1);

                Trace.WriteLine("A similar request, e.g. with a claims challenge, will be throttled");
                var ex = await AssertException.TaskThrowsAsync <MsalThrottledServiceException>(
                    () => app.AcquireTokenSilent(TestConstants.s_scope, account)
                    .WithClaims(TestConstants.Claims)     // claims are not part of the strict thumbprint
                    .ExecuteAsync())
                         .ConfigureAwait(false);

                Assert.AreEqual(429, ex.StatusCode);
                AssertThrottlingCacheEntryCount(throttlingManager, httpStatusEntryCount: 1);

                Trace.WriteLine("A different request, e.g. with other scopes, will not be throttled");
                httpManagerAndBundle.HttpManager.AddTokenResponse(TokenResponseType.Valid);
                await app.AcquireTokenSilent(new[] { "Other.Scopes" }, account).ExecuteAsync()
                .ConfigureAwait(false);

                Trace.WriteLine("Create a new PCA and try a different flow");
                var pca2 = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                           .WithHttpManager(httpManagerAndBundle.HttpManager)
                           .BuildConcrete();
                new TokenCacheHelper().PopulateCache(
                    pca2.UserTokenCacheInternal.Accessor,
                    expiredAccessTokens: true);

                await AssertException.TaskThrowsAsync <MsalThrottledServiceException>(
                    () => pca2.AcquireTokenSilent(TestConstants.s_scope, account)
                    .ExecuteAsync())
                .ConfigureAwait(false);
            }
        }
        private async Task <(MockHttpMessageHandler MockHttpHandler, Guid Correlationid)> RunSilentFlowWithTokenErrorAsync(AcquireTokenSilentParameterBuilder request, string errorCode)
        {
            _app.UserTokenCacheInternal.Accessor.ClearAccessTokens();

            var correlationId = Guid.NewGuid();
            var tokenRequest  = _harness.HttpManager.AddFailureTokenEndpointResponse(
                errorCode,
                TestConstants.AuthorityUtidTenant,
                correlationId.ToString());

            var ex = await AssertException.TaskThrowsAsync <MsalServiceException>(
                () => request.WithCorrelationId(correlationId).ExecuteAsync(),
                allowDerived : true)
                     .ConfigureAwait(false);

            Assert.AreEqual(
                correlationId,
                Guid.Parse(ex.CorrelationId),
                "Test error - Exception correlation ID does not match WithCorrelationId value");

            return(tokenRequest, correlationId);
        }
        public async Task FederatedUsernamePasswordCommonAuthorityTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(TestConstants.AuthorityCommonTenant);
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);
                AddMockHandlerMex(httpManager);
                AddMockHandlerWsTrustUserName(httpManager);

                // AAD
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedUrl     = "https://login.microsoftonline.com/common/oauth2/v2.0/token",
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateInvalidRequestTokenResponseMessage()
                });

                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(MsalError.InvalidRequest, result.ErrorCode);

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

                // user realm discovery - unknown user type
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Get,
                    ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(
                            "{\"ver\":\"1.0\"," +
                            "\"account_type\":\"Bogus\"}")
                    }
                });

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

                // Act
                MsalClientException exception = await AssertException.TaskThrowsAsync <MsalClientException>(
                    async() => await app
                    .AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope)
                    .WithUsername(TestConstants.s_user.Username)
                    .ExecuteAsync(CancellationToken.None)
                    .ConfigureAwait(false)).ConfigureAwait(false);

                // Assert
                Assert.AreEqual(MsalError.UnknownUserType, exception.ErrorCode);
            }
        }
Example #22
0
        // regression for #2837
        public async Task AuthorityOverrideAndRegionalAsync()
        {
            const string region = "eastus";

            Environment.SetEnvironmentVariable("REGION_NAME", region);

            var app = ConfidentialClientApplicationBuilder
                      .Create(TestConstants.ClientId)
                      .WithAzureRegion(ConfidentialClientApplication.AttemptRegionDiscovery)
                      .WithClientSecret(TestConstants.ClientSecret)
                      .Build();

#pragma warning disable CS0618 // Type or member is obsolete
            var ex = await AssertException.TaskThrowsAsync <MsalClientException>(() =>
                                                                                 app
                                                                                 .AcquireTokenForClient(TestConstants.s_scope)
                                                                                 .WithAuthority($"https://login.microsoft.com/17b189bc-2b81-4ec5-aa51-3e628cbc931b")
#pragma warning restore CS0618 // Type or member is obsolete
                                                                                 .ExecuteAsync())
                     .ConfigureAwait(false);

            Assert.AreEqual(MsalError.RegionalAndAuthorityOverride, ex.ErrorCode);
        }
        public async Task RetryAfter_ConfidentialClient_ErrorMessage_Async()
        {
            using (var httpManagerAndBundle = new MockHttpAndServiceBundle())
            {
                var httpManager = httpManagerAndBundle.HttpManager;
                var app         = ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId)
                                  .WithClientSecret(TestConstants.ClientSecret)
                                  .WithHttpManager(httpManager)
                                  .BuildConcrete();

                httpManager.AddInstanceDiscoveryMockHandler();
                var tokenResponse = httpManager.AddMockHandlerForThrottledResponseMessage();

                var serverEx = await AssertException.TaskThrowsAsync <MsalThrottledServiceException>(
                    () => app.AcquireTokenForClient(TestConstants.s_scope).ExecuteAsync())
                               .ConfigureAwait(false);

                Assert.AreEqual(serverEx.StatusCode, 429);
                Assert.AreEqual(serverEx.ErrorCode, MsalError.RequestThrottled);
                Assert.AreEqual(serverEx.Message, MsalErrorMessage.AadThrottledError);
                Assert.AreEqual(serverEx.ResponseBody, MockHelpers.TooManyRequestsContent);
            }
        }
Example #24
0
        public async Task AuthorityValidationFailure_IsRethrown_Async()
        {
            // Arrange
            var validationException = new MsalServiceException(MsalError.InvalidInstance, "authority validation failed");

            _networkCacheMetadataProvider = new NetworkCacheMetadataProvider();

            // network fails with invalid_instance exception
            _networkMetadataProvider
            .When(x => x.GetMetadataAsync(Arg.Any <Uri>(), _testRequestContext))
            .Do(x => throw validationException);

            // Act
            var actualException = await AssertException.TaskThrowsAsync <MsalServiceException>(() =>
                                                                                               _discoveryManager.GetMetadataEntryAsync(
                                                                                                   AuthorityInfo.FromAuthorityUri("https://some_env.com/tid", true),
                                                                                                   _testRequestContext))
                                  .ConfigureAwait(false);

            // Assert
            Assert.AreSame(validationException, actualException);
            _knownMetadataProvider.DidNotReceiveWithAnyArgs();
        }
        public async Task B2C_NoScopes_NoAccessToken_Async()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(TestConstants.B2CLoginAuthority), true)
                                              .WithHttpManager(httpManager)
                                              .BuildConcrete();

                MsalMockHelpers.ConfigureMockWebUI(
                    app.ServiceBundle.PlatformProxy,
                    AuthorizationResult.FromUri(app.AppConfig.RedirectUri + "?code=some-code"));

                // Arrange 1 - interactive call with 0 scopes
                httpManager.AddMockHandlerForTenantEndpointDiscovery(TestConstants.B2CLoginAuthority);
                httpManager.AddSuccessTokenResponseMockHandlerForPost(
                    TestConstants.B2CLoginAuthority,
                    responseMessage: MockHelpers.CreateSuccessResponseMessage(MockHelpers.B2CTokenResponseWithoutAT));

                // Act
                AuthenticationResult result = await app
                                              .AcquireTokenInteractive(null) // no scopes -> no Access Token!
                                              .ExecuteAsync()
                                              .ConfigureAwait(false);

                // Assert
                AssertNoAccessToken(result);
                Assert.AreEqual(0, httpManager.QueueSize);

                var ex = await AssertException.TaskThrowsAsync <MsalUiRequiredException>(() =>
                                                                                         app.AcquireTokenSilent(null, result.Account).ExecuteAsync()
                                                                                         ).ConfigureAwait(false);

                Assert.AreEqual(MsalError.ScopesRequired, ex.ErrorCode);
                Assert.AreEqual(UiRequiredExceptionClassification.AcquireTokenSilentFailed, ex.Classification);
            }
        }
Example #26
0
        public async Task BadTokenError_RemoveAccountFromCacheAsync()
        {
            // Arrange
            using (MockHttpAndServiceBundle harness = base.CreateTestHarness())
            {
                Trace.WriteLine("1. Create PCA");

                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithHttpManager(harness.HttpManager)
                                              .BuildConcrete();

                var tokenCacheHelper = new TokenCacheHelper();
                tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor, addSecondAt: false);

                Trace.WriteLine("2. Configure AAD to respond with the typical Invalid Grant error and Bad Token sub error");
                AddHttpMocks_BadTokenError(harness.HttpManager);
                var account = new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null);

                // Act
                var exception = await AssertException.TaskThrowsAsync <MsalUiRequiredException>(() => app
                                                                                                .AcquireTokenSilent(
                                                                                                    TestConstants.s_scope.ToArray(),
                                                                                                    account)
                                                                                                .WithForceRefresh(true)
                                                                                                .ExecuteAsync())
                                .ConfigureAwait(false);

                Assert.AreEqual(MsalError.BadToken, exception.SubError);

                var accounts = await app.GetAccountsAsync().ConfigureAwait(false);

                Assert.IsFalse(accounts.Any());

                var refreshTokens = app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens();
                Assert.IsFalse(refreshTokens.Any());
            }
        }
Example #27
0
        public async Task FociAppLeavesFamilyAsync()
        {
            using (_harness = new MockHttpAndServiceBundle())
            {
                InitApps();

                // A and B are part of the family
                await InteractiveAsync(_appA, ServerTokenResponse.FociToken).ConfigureAwait(false);
                await SilentAsync(_appB, ServerTokenResponse.FociToken).ConfigureAwait(false);

                // B leaves the family -> STS will not refresh its token based on the FRT
                await AssertException.TaskThrowsAsync <MsalUiRequiredException>(() => SilentAsync(_appB, ServerTokenResponse.ErrorClientMismatch)).ConfigureAwait(false);

                // B can resume acquiring tokens silently via the normal RT, after an interactive flow
                await InteractiveAsync(_appB, ServerTokenResponse.NonFociToken).ConfigureAwait(false);
                await SilentAsync(_appB, ServerTokenResponse.NonFociToken).ConfigureAwait(false);

                // Assert
                await AssertAccountsAsync().ConfigureAwait(false);

                AssertAppHasRT(_appB);
                AssertFRTExists();
            }
        }
Example #28
0
        [WorkItem(1407)] // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1407
        public async Task DeviceCodeExceptionsOn200OKAsync()
        {
            using (var harness = CreateTestHarness())
            {
                TestCommon.MockInstanceDiscoveryAndOpenIdRequest(harness.HttpManager);
                var handler = new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateInvalidClientResponseMessage()
                };

                harness.HttpManager.AddMockHandler(handler);

                var parameters = harness.CreateAuthenticationRequestParameters(
                    TestConstants.AuthorityHomeTenant,
                    TestConstants.s_scope,
                    new TokenCache(harness.ServiceBundle, false),
                    account: null);

                DeviceCodeResult actualDeviceCodeResult = null;

                var deviceCodeParameters = new AcquireTokenWithDeviceCodeParameters
                {
                    DeviceCodeResultCallback = result =>
                    {
                        actualDeviceCodeResult = result;
                        return(Task.FromResult(0));
                    }
                };

                var request = new DeviceCodeRequest(harness.ServiceBundle, parameters, deviceCodeParameters);

                var ex = await AssertException.TaskThrowsAsync <MsalServiceException>(
                    () => request.ExecuteAsync(CancellationToken.None)).ConfigureAwait(false);
            }
        }
        public async Task RemoveAADAccountAsync()
        {
            string aadHomeAccId = $"{TestConstants.Uid}.{TestConstants.Utid}";

            // Arrange
            using (var harness = CreateTestHarness())
            {
                var wamAccountProvider = new WebAccountProvider("id", "*****@*****.**", null);
                var requestParams      = harness.CreateAuthenticationRequestParameters(TestConstants.AuthorityConsumerTidTenant); // MSA
                requestParams.Account = new Account(
                    aadHomeAccId,                                                                                                 // matching in on home acc id
                    "*****@*****.**",                                                                                  // matching is not on UPN
                    null);                                                                                                        // account does not have wam_id, might be coming directly from WAM

                var webAccount = new WebAccount(wamAccountProvider, "*****@*****.**", WebAccountState.Connected);
                IReadOnlyList <WebAccount> webAccounts = new List <WebAccount>()
                {
                    webAccount
                };


                _wamProxy.FindAllWebAccountsAsync(wamAccountProvider, TestConstants.ClientId).Returns(Task.FromResult(webAccounts));

                // WAM can give MSAL the home account ID of a Wam account, which MSAL matches to a WAM account
                _aadPlugin.GetHomeAccountIdOrNull(webAccount).Returns(aadHomeAccId);


                var atsParams = new AcquireTokenSilentParameters();
                _webAccountProviderFactory.GetAccountProviderAsync("organizations").ReturnsForAnyArgs(Task.FromResult(wamAccountProvider));

                // Act Assert
                await AssertException.TaskThrowsAsync <FileNotFoundException>( // Since WebAccount is a real object, it throws this exception
                    () => _wamBroker.RemoveAccountAsync(harness.ServiceBundle.Config, requestParams.Account))
                .ConfigureAwait(false);
            }
        }
        public async Task ATI_RequiresSyncContext_Async()
        {
            var wamBroker = new WamBroker(
                new CoreUIParent(), // no sync context here
                _logger,
                _aadPlugin,
                _msaPlugin,
                _wamProxy,
                _webAccountProviderFactory,
                _accountPickerFactory);

            using (var harness = CreateTestHarness())
            {
                var requestParams = harness.CreateAuthenticationRequestParameters(TestConstants.AuthorityHomeTenant); // AAD
                var atiParams     = new AcquireTokenInteractiveParameters();

                // Act
                var ex = await AssertException.TaskThrowsAsync <MsalClientException>(
                    () => wamBroker.AcquireTokenInteractiveAsync(requestParams, atiParams)).ConfigureAwait(false);

                // Assert
                Assert.AreEqual(MsalError.WamUiThread, ex.ErrorCode);
            }
        }