Beispiel #1
0
        public async Task AuthorityMigrationAsync()
        {
            LabResponse labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

            LabUser user = labResponse.User;

            IPublicClientApplication pca = PublicClientApplicationBuilder
                                           .Create(labResponse.AppId)
                                           .Build();

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

            AuthenticationResult authResult = await pca.AcquireTokenByUsernamePassword(
                s_scopes,
                user.Upn,
                new NetworkCredential("", user.GetOrFetchPassword()).SecurePassword)
                                              .WithAuthority("https://sts.windows.net/" + user.CurrentTenantId + "/")
                                              .ExecuteAsync()
                                              .ConfigureAwait(false);

            Assert.IsNotNull(authResult.AccessToken);

            Trace.WriteLine("Acquire a token silently using the common authority alias");

            authResult = await pca.AcquireTokenSilent(s_scopes, (await pca.GetAccountsAsync().ConfigureAwait(false)).First())
                         .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
                         .ExecuteAsync()
                         .ConfigureAwait(false);

            Assert.IsNotNull(authResult.AccessToken);
        }
        public async Task AuthorityMigrationAsync()
        {
            LabResponse labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

            LabUser user = labResponse.User;

            IPublicClientApplication pca = PublicClientApplicationBuilder
                                           .Create(labResponse.App.AppId)
                                           .WithTestLogging()
                                           .Build();

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

            AuthenticationResult authResult = await pca.AcquireTokenByUsernamePassword(
                s_scopes,
                user.Upn,
                new NetworkCredential("", user.GetOrFetchPassword()).SecurePassword)
                                              // BugBug https://identitydivision.visualstudio.com/Engineering/_workitems/edit/776308/
                                              // sts.windows.net fails when doing instance discovery, e.g.:
                                              // https://sts.windows.net/common/discovery/instance?api-version=1.1&authorization_endpoint=https%3A%2F%2Fsts.windows.net%2Ff645ad92-e38d-4d1a-b510-d1b09a74a8ca%2Foauth2%2Fv2.0%2Fauthorize
                                              .WithAuthority("https://login.windows.net/" + labResponse.Lab.TenantId + "/")
                                              .ExecuteAsync()
                                              .ConfigureAwait(false);

            Assert.IsNotNull(authResult.AccessToken);

            Trace.WriteLine("Acquire a token silently using the common authority alias");

            authResult = await pca.AcquireTokenSilent(s_scopes, (await pca.GetAccountsAsync().ConfigureAwait(false)).First())
                         .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
                         .ExecuteAsync()
                         .ConfigureAwait(false);

            Assert.IsNotNull(authResult.AccessToken);
        }
Beispiel #3
0
        public void PerformSignInFlow(
            ITestController controller,
            LabUser user,
            string testToRun)
        {
            UserInformationFieldIds userInformationFieldIds = DetermineUserInformationFieldIds(user);

            controller.Tap(CoreUiTestConstants.TestsToRunPicker);
            controller.Tap(testToRun);

            try
            {
                controller.WaitForWebElementByCssId(CoreUiTestConstants.WebUPNInputId);
                //i0116 = UPN text field on AAD sign in endpoint
                controller.EnterText(CoreUiTestConstants.WebUPNInputId, 20, user.Upn, XamarinSelector.ByHtmlIdAttribute);
                //idSIButton9 = Sign in button
                controller.Tap(CoreUiTestConstants.WebSubmitId, XamarinSelector.ByHtmlIdAttribute);
                //i0118 = password text field
                controller.WaitForWebElementByCssId(userInformationFieldIds.GetPasswordInputId());
                controller.EnterText(userInformationFieldIds.GetPasswordInputId(), user.GetOrFetchPassword(), XamarinSelector.ByHtmlIdAttribute);
                controller.Tap(userInformationFieldIds.GetPasswordSignInButtonId(), XamarinSelector.ByHtmlIdAttribute);
            }
            catch
            {
                Console.WriteLine("Failed to find UPN input. Attempting to click on UPN from select account screen");
                controller.Tap(user.Upn, XamarinSelector.ByHtmlValue);
            }
        }
Beispiel #4
0
        private async Task <IConfidentialClientApplication> RunOnBehalfOfTestAsync(LabUser user, bool silentCallShouldSucceed)
        {
            SecureString         securePassword = new NetworkCredential("", user.GetOrFetchPassword()).SecurePassword;
            AuthenticationResult authResult;

            var pca = PublicClientApplicationBuilder
                      .Create(PublicClientID)
                      .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
                      .Build();

            s_inMemoryTokenCache.Bind(pca.UserTokenCache);

            try
            {
                authResult = await pca
                             .AcquireTokenSilent(s_oboServiceScope, user.Upn)
                             .ExecuteAsync()
                             .ConfigureAwait(false);
            }
            catch (MsalUiRequiredException)
            {
                Assert.IsFalse(silentCallShouldSucceed, "ATS should have found a token, but it didn't");
                authResult = await pca
                             .AcquireTokenByUsernamePassword(s_oboServiceScope, user.Upn, securePassword)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);
            }

            MsalAssert.AssertAuthResult(authResult, user);
            Assert.IsTrue(authResult.Scopes.Any(s => string.Equals(s, s_oboServiceScope.Single(), StringComparison.OrdinalIgnoreCase)));

            var cca = ConfidentialClientApplicationBuilder
                      .Create(OboConfidentialClientID)
                      .WithAuthority(new Uri("https://login.microsoftonline.com/" + authResult.TenantId), true)
                      .WithClientSecret(_confidentialClientSecret)
                      .Build();

            s_inMemoryTokenCache.Bind(cca.UserTokenCache);

            try
            {
                authResult = await cca
                             .AcquireTokenSilent(s_scopes, user.Upn)
                             .ExecuteAsync()
                             .ConfigureAwait(false);
            }
            catch (MsalUiRequiredException)
            {
                Assert.IsFalse(silentCallShouldSucceed, "ATS should have found a token, but it didn't");

                authResult = await cca.AcquireTokenOnBehalfOf(s_scopes, new UserAssertion(authResult.AccessToken))
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);
            }

            MsalAssert.AssertAuthResult(authResult, user);
            Assert.IsTrue(authResult.Scopes.Any(s => string.Equals(s, s_scopes.Single(), StringComparison.OrdinalIgnoreCase)));

            return(cca);
        }
Beispiel #5
0
        private async Task RunOnBehalfOfTestAsync(LabResponse labResponse)
        {
            LabUser user = labResponse.User;
            string  oboHost;
            string  secret;
            string  authority;
            string  publicClientID;
            string  confidentialClientID;

            string[] oboScope;

            switch (labResponse.User.AzureEnvironment)
            {
            case AzureEnvironment.azureusgovernment:
                oboHost              = ArlingtonCloudHost;
                secret               = _keyVault.GetSecret(TestConstants.MsalArlingtonOBOKeyVaultUri).Value;
                authority            = labResponse.Lab.Authority + "organizations";
                publicClientID       = ArlingtonPublicClientIDOBO;
                confidentialClientID = ArlingtonConfidentialClientIDOBO;
                oboScope             = s_arlingtonOBOServiceScope;
                break;

            default:
                oboHost              = PublicCloudHost;
                secret               = _keyVault.GetSecret(TestConstants.MsalOBOKeyVaultUri).Value;
                authority            = TestConstants.AuthorityOrganizationsTenant;
                publicClientID       = PublicCloudPublicClientIDOBO;
                confidentialClientID = PublicCloudConfidentialClientIDOBO;
                oboScope             = s_publicCloudOBOServiceScope;
                break;
            }

            //TODO: acquire scenario specific client ids from the lab resonse

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

            var msalPublicClient = PublicClientApplicationBuilder.Create(publicClientID)
                                   .WithAuthority(authority)
                                   .WithRedirectUri(TestConstants.RedirectUri)
                                   .Build();

            var builder = msalPublicClient.AcquireTokenByUsernamePassword(oboScope, user.Upn, securePassword);

            builder.WithAuthority(authority);

            var authResult = await builder.ExecuteAsync().ConfigureAwait(false);

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(confidentialClientID)
                                  .WithAuthority(new Uri(oboHost + authResult.TenantId), true)
                                  .WithClientSecret(secret)
                                  .Build();

            authResult = await confidentialApp.AcquireTokenOnBehalfOf(s_scopes, new UserAssertion(authResult.AccessToken))
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult, user);
        }
        public void PerformB2CLocalAccountSignInFlow(ITestController controller, LabUser user, UserInformationFieldIds userInformationFieldIds)
        {
            controller.EnterText(CoreUiTestConstants.WebUpnB2CLocalInputId, 20, user.Upn, XamarinSelector.ByHtmlIdAttribute);

            controller.EnterText(userInformationFieldIds.PasswordInputId, user.GetOrFetchPassword(), XamarinSelector.ByHtmlIdAttribute);

            controller.Tap(userInformationFieldIds.PasswordSignInButtonId, XamarinSelector.ByHtmlIdAttribute);
        }
Beispiel #7
0
        private static void EnterPassword(IWebDriver driver, LabUser user, UserInformationFieldIds fields)
        {
            Trace.WriteLine("Logging in ... Entering password");
            string password      = user.GetOrFetchPassword();
            string passwordField = fields.GetPasswordInputId();

            driver.WaitForElementToBeVisibleAndEnabled(By.Id(passwordField)).SendKeys(password);

            Trace.WriteLine("Logging in ... Clicking next after password");
            driver.WaitForElementToBeVisibleAndEnabled(By.Id(fields.GetPasswordSignInButtonId())).Click();
        }
Beispiel #8
0
        public void PerformB2CGoogleProviderSignInFlow(ITestController controller, LabUser user, UserInformationFieldIds userInformationFieldIds)
        {
            controller.Tap(CoreUiTestConstants.GoogleAccountId, XamarinSelector.ByHtmlIdAttribute);

            controller.EnterText(CoreUiTestConstants.WebUpnB2CGoogleInputId, 20, user.Upn, XamarinSelector.ByHtmlIdAttribute);

            controller.Tap(CoreUiTestConstants.B2CGoogleNextId, XamarinSelector.ByHtmlIdAttribute);

            controller.EnterText(userInformationFieldIds.GetPasswordInputId(true), user.GetOrFetchPassword(), XamarinSelector.ByHtmlIdAttribute);

            controller.Tap(userInformationFieldIds.GetPasswordSignInButtonId(true), XamarinSelector.ByHtmlIdAttribute);
        }
Beispiel #9
0
        public void PerformB2CFacebookProviderSignInFlow(ITestController controller, LabUser user, UserInformationFieldIds userInformationFieldIds)
        {
            controller.WaitForWebElementByCssId(CoreUiTestConstants.FacebookAccountId);

            controller.Tap(CoreUiTestConstants.FacebookAccountId, XamarinSelector.ByHtmlIdAttribute);

            controller.WaitForWebElementByCssId(CoreUiTestConstants.WebUpnB2CFacebookInputId);

            controller.EnterText(CoreUiTestConstants.WebUpnB2CFacebookInputId, 20, user.Upn, XamarinSelector.ByHtmlIdAttribute);

            controller.EnterText(userInformationFieldIds.GetPasswordInputId(true), user.GetOrFetchPassword(), XamarinSelector.ByHtmlIdAttribute);

            controller.WaitForWebElementByCssId(userInformationFieldIds.GetPasswordSignInButtonId(true));

            controller.Tap(userInformationFieldIds.GetPasswordSignInButtonId(true), XamarinSelector.ByHtmlIdAttribute);
        }
Beispiel #10
0
        public void PerformB2CLocalAccountSignInFlow(ITestController controller, LabUser user, UserInformationFieldIds userInformationFieldIds)
        {
            controller.EnterText(CoreUiTestConstants.WebUpnB2CLocalInputId, 20, user.Upn, XamarinSelector.ByHtmlIdAttribute);

            if (_platform == Xamarin.UITest.Platform.iOS)
            {
                controller.Tap(CoreUiTestConstants.B2CWebPasswordId, XamarinSelector.ByHtmlIdAttribute);
                controller.EnterText(CoreUiTestConstants.B2CWebPasswordId, user.GetOrFetchPassword(), XamarinSelector.ByHtmlIdAttribute);
                controller.DismissKeyboard();
            }
            else
            {
                controller.EnterText(userInformationFieldIds.GetPasswordInputId(true), user.GetOrFetchPassword(), XamarinSelector.ByHtmlIdAttribute);
            }

            controller.Tap(userInformationFieldIds.GetPasswordSignInButtonId(true), XamarinSelector.ByHtmlIdAttribute);
        }
Beispiel #11
0
        private async Task <IConfidentialClientApplication> RunOnBehalfOfTestAsync(
            LabUser user,
            bool silentCallShouldSucceed,
            bool forceRefresh = false)
        {
            SecureString         securePassword = new NetworkCredential("", user.GetOrFetchPassword()).SecurePassword;
            AuthenticationResult authResult;

            var pca = PublicClientApplicationBuilder
                      .Create(PublicClientID)
                      .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
                      .WithTestLogging()
                      .Build();

            s_inMemoryTokenCache.Bind(pca.UserTokenCache);
            try
            {
                authResult = await pca
                             .AcquireTokenSilent(s_oboServiceScope, user.Upn)
                             .ExecuteAsync()
                             .ConfigureAwait(false);

                Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);
            }
            catch (MsalUiRequiredException)
            {
                Assert.IsFalse(silentCallShouldSucceed, "ATS should have found a token, but it didn't");
                authResult = await pca
                             .AcquireTokenByUsernamePassword(s_oboServiceScope, user.Upn, securePassword)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

                Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
            }

            MsalAssert.AssertAuthResult(authResult, user);
            Assert.IsTrue(authResult.Scopes.Any(s => string.Equals(s, s_oboServiceScope.Single(), StringComparison.OrdinalIgnoreCase)));

            var cca = ConfidentialClientApplicationBuilder
                      .Create(OboConfidentialClientID)
                      .WithAuthority(new Uri("https://login.microsoftonline.com/" + authResult.TenantId), true)
                      .WithTestLogging(out HttpSnifferClientFactory factory)
                      .WithClientSecret(_confidentialClientSecret)
                      .Build();

            s_inMemoryTokenCache.Bind(cca.UserTokenCache);

            authResult = await cca.AcquireTokenOnBehalfOf(s_scopes, new UserAssertion(authResult.AccessToken))
                         .WithForceRefresh(forceRefresh)
                         .WithCcsRoutingHint("597f86cd-13f3-44c0-bece-a1e77ba43228", "f645ad92-e38d-4d1a-b510-d1b09a74a8ca")
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            if (!forceRefresh)
            {
                Assert.AreEqual(
                    silentCallShouldSucceed,
                    authResult.AuthenticationResultMetadata.TokenSource == TokenSource.Cache);
            }
            else
            {
                Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
            }

            MsalAssert.AssertAuthResult(authResult, user);
            Assert.IsNotNull(authResult.IdToken); // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1950
            Assert.IsTrue(authResult.Scopes.Any(s => string.Equals(s, s_scopes.Single(), StringComparison.OrdinalIgnoreCase)));
            AssertExtraHTTPHeadersAreSent(factory);

            return(cca);
        }
        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);

#if NET_CORE
            Assert.IsTrue(((System.Net.Sockets.SocketException)exception.InnerException).SocketErrorCode == System.Net.Sockets.SocketError.HostNotFound);
#else
            Assert.IsTrue(((System.Net.WebException)exception.InnerException).Status == System.Net.WebExceptionStatus.NameResolutionFailure);
#endif
        }
        public async Task FailedAuthorityValidationTestAsync()
        {
            LabResponse labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

            LabUser user = labResponse.User;

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

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

            MsalServiceException exception = await AssertException.TaskThrowsAsync <MsalServiceException>(() =>
                                                                                                          pca.AcquireTokenByUsernamePassword(
                                                                                                              s_scopes,
                                                                                                              user.Upn,
                                                                                                              new NetworkCredential("", user.GetOrFetchPassword()).SecurePassword)
                                                                                                          .ExecuteAsync())
                                             .ConfigureAwait(false);

            Assert.IsTrue(exception.Message.Contains("AADSTS50049"));
            Assert.AreEqual("invalid_instance", exception.ErrorCode);
        }
Beispiel #14
0
        public static void PerformLogin(this IWebDriver driver, LabUser user, Prompt prompt, bool withLoginHint = false)
        {
            UserInformationFieldIds fields = new UserInformationFieldIds(user);

            if (!withLoginHint)
            {
                Trace.WriteLine("Logging in ... Entering username");
                driver.FindElement(By.Id(fields.AADUsernameInputId)).SendKeys(user.Upn);

                Trace.WriteLine("Logging in ... Clicking <Next> after username");
                driver.FindElement(By.Id(fields.AADSignInButtonId)).Click();
            }

            if (user.FederationProvider == FederationProvider.AdfsV2)
            {
                Trace.WriteLine("Logging in ... AFDSv2 - Entering the username again, this time in the ADFSv2 form");
                driver.FindElement(By.Id(CoreUiTestConstants.AdfsV2WebUsernameInputId)).SendKeys(user.Upn);
            }

            Trace.WriteLine("Logging in ... Entering password");
            driver.WaitForElementToBeVisibleAndEnabled(By.Id(fields.PasswordInputId)).SendKeys(user.GetOrFetchPassword());

            Trace.WriteLine("Logging in ... Clicking next after password");
            driver.WaitForElementToBeVisibleAndEnabled(By.Id(fields.PasswordSignInButtonId)).Click();

            if (prompt == Prompt.Consent)
            {
                Trace.WriteLine("Consenting...");
                driver.WaitForElementToBeVisibleAndEnabled(By.Id(fields.AADSignInButtonId)).Click();
            }
        }
Beispiel #15
0
        //Since this test performs a large number of operations it should not be rerun on other clouds.
        private async Task RunOnBehalfOfTestWithTokenCacheAsync(LabResponse labResponse)
        {
            LabUser user = labResponse.User;
            string  oboHost;
            string  secret;
            string  authority;
            string  publicClientID;
            string  confidentialClientID;

            string[] oboScope;

            oboHost              = PublicCloudHost;
            secret               = _keyVault.GetSecret(TestConstants.MsalOBOKeyVaultUri).Value;
            authority            = TestConstants.AuthorityOrganizationsTenant;
            publicClientID       = PublicCloudPublicClientIDOBO;
            confidentialClientID = PublicCloudConfidentialClientIDOBO;
            oboScope             = s_publicCloudOBOServiceScope;

            //TODO: acquire scenario specific client ids from the lab response

            SecureString securePassword = new NetworkCredential("", user.GetOrFetchPassword()).SecurePassword;
            var          factory        = new HttpSnifferClientFactory();

            var msalPublicClient = PublicClientApplicationBuilder.Create(publicClientID)
                                   .WithAuthority(authority)
                                   .WithRedirectUri(TestConstants.RedirectUri)
                                   .WithTestLogging()
                                   .WithHttpClientFactory(factory)
                                   .Build();

            var authResult = await msalPublicClient.AcquireTokenByUsernamePassword(oboScope, user.Upn, securePassword)
                             .ExecuteAsync()
                             .ConfigureAwait(false);

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(confidentialClientID)
                                  .WithAuthority(new Uri(oboHost + authResult.TenantId), true)
                                  .WithClientSecret(secret)
                                  .WithTestLogging()
                                  .BuildConcrete();

            var userCacheRecorder = confidentialApp.UserTokenCache.RecordAccess();

            UserAssertion userAssertion = new UserAssertion(authResult.AccessToken);

            string atHash = userAssertion.AssertionHash;

            authResult = await confidentialApp.AcquireTokenOnBehalfOf(s_scopes, userAssertion)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult, user);
            Assert.AreEqual(atHash, userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
            Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);

            //Run OBO again. Should get token from cache
            authResult = await confidentialApp.AcquireTokenOnBehalfOf(s_scopes, userAssertion)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.IsNotNull(authResult);
            Assert.IsNotNull(authResult.AccessToken);
            Assert.IsNotNull(authResult.IdToken);
            Assert.IsTrue(!userCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.IsTrue(userCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
            Assert.AreEqual(atHash, userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
            Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);

            //Expire access tokens
            TokenCacheHelper.ExpireAllAccessTokens(confidentialApp.UserTokenCacheInternal);

            //Run OBO again. Should do OBO flow since the AT is expired and RTs aren't cached for normal OBO flow
            authResult = await confidentialApp.AcquireTokenOnBehalfOf(s_scopes, userAssertion)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.IsNotNull(authResult);
            Assert.IsNotNull(authResult.AccessToken);
            Assert.IsNotNull(authResult.IdToken);
            Assert.IsTrue(!userCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.IsTrue(userCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
            Assert.AreEqual(atHash, userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
            Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
            AssertLastHttpContent("on_behalf_of");

            //creating second app with no refresh tokens
            var atItems          = confidentialApp.UserTokenCacheInternal.Accessor.GetAllAccessTokens();
            var confidentialApp2 = ConfidentialClientApplicationBuilder
                                   .Create(confidentialClientID)
                                   .WithAuthority(new Uri(oboHost + authResult.TenantId), true)
                                   .WithClientSecret(secret)
                                   .WithTestLogging()
                                   .WithHttpClientFactory(factory)
                                   .BuildConcrete();

            TokenCacheHelper.ExpireAccessToken(confidentialApp2.UserTokenCacheInternal, atItems.FirstOrDefault());

            //Should perform OBO flow since the access token is expired and the refresh token does not exist
            authResult = await confidentialApp2.AcquireTokenOnBehalfOf(s_scopes, userAssertion)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.IsNotNull(authResult);
            Assert.IsNotNull(authResult.AccessToken);
            Assert.IsNotNull(authResult.IdToken);
            Assert.IsTrue(!userCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.IsTrue(userCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
            Assert.AreEqual(atHash, userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
            Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
            AssertLastHttpContent("on_behalf_of");

            TokenCacheHelper.ExpireAllAccessTokens(confidentialApp2.UserTokenCacheInternal);
            TokenCacheHelper.UpdateUserAssertions(confidentialApp2);

            //Should perform OBO flow since the access token and the refresh token contains the wrong user assertion hash
            authResult = await confidentialApp2.AcquireTokenOnBehalfOf(s_scopes, userAssertion)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.IsNotNull(authResult);
            Assert.IsNotNull(authResult.AccessToken);
            Assert.IsNotNull(authResult.IdToken);
            Assert.IsTrue(!userCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.IsTrue(userCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
            Assert.AreEqual(atHash, userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
            Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
            AssertLastHttpContent("on_behalf_of");
        }
Beispiel #16
0
        public static void PerformLogin(this IWebDriver driver, LabUser user, Prompt prompt, bool withLoginHint = false, bool adfsOnly = false)
        {
            UserInformationFieldIds fields = new UserInformationFieldIds(user);

            if (adfsOnly && !withLoginHint)
            {
                Trace.WriteLine("Logging in ... Entering username");
                driver.FindElement(By.Id(CoreUiTestConstants.AdfsV4UsernameInputdId)).SendKeys(user.Upn);
            }
            else
            {
                if (!withLoginHint)
                {
                    Trace.WriteLine("Logging in ... Entering username");
                    driver.FindElement(By.Id(fields.AADUsernameInputId)).SendKeys(user.Upn.Contains("EXT")? user.HomeUPN : user.Upn);

                    Trace.WriteLine("Logging in ... Clicking <Next> after username");
                    driver.FindElement(By.Id(fields.AADSignInButtonId)).Click();
                }

                if (user.FederationProvider == FederationProvider.AdfsV2 && user.IsFederated)
                {
                    Trace.WriteLine("Logging in ... AFDSv2 - Entering the username again, this time in the ADFSv2 form");
                    driver.FindElement(By.Id(CoreUiTestConstants.AdfsV2WebUsernameInputId)).SendKeys(user.Upn);
                }
            }

            Trace.WriteLine("Logging in ... Entering password");
            driver.WaitForElementToBeVisibleAndEnabled(By.Id(fields.GetPasswordInputId())).SendKeys(user.GetOrFetchPassword());

            Trace.WriteLine("Logging in ... Clicking next after password");
            driver.WaitForElementToBeVisibleAndEnabled(By.Id(fields.GetPasswordSignInButtonId())).Click();

            if (user.HomeUPN.Contains("outlook.com"))
            {
                Trace.WriteLine("Loggin in ... clicking accept promps for outlook.com MSA user");
                driver.WaitForElementToBeVisibleAndEnabled(By.Id(CoreUiTestConstants.ConsentAcceptId)).Click();
            }

            if (prompt == Prompt.Consent)
            {
                Trace.WriteLine("Consenting...");
                driver.WaitForElementToBeVisibleAndEnabled(By.Id(fields.AADSignInButtonId)).Click();
            }
        }
Beispiel #17
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);
        }
Beispiel #18
0
        private async Task RunOnBehalfOfTestAsync(LabResponse labResponse)
        {
            LabUser user = labResponse.User;
            string  oboHost;
            string  secret;
            string  authority;
            string  publicClientID;
            string  confidentialClientID;

            string[] oboScope;

            switch (labResponse.User.AzureEnvironment)
            {
            case AzureEnvironment.azureusgovernment:
                oboHost              = ArlingtonCloudHost;
                secret               = _keyVault.GetSecret(TestConstants.MsalArlingtonOBOKeyVaultUri).Value;
                authority            = labResponse.Lab.Authority + "organizations";
                publicClientID       = ArlingtonPublicClientIDOBO;
                confidentialClientID = ArlingtonConfidentialClientIDOBO;
                oboScope             = s_arlingtonOBOServiceScope;
                break;

            default:
                oboHost              = PublicCloudHost;
                secret               = _keyVault.GetSecret(TestConstants.MsalOBOKeyVaultUri).Value;
                authority            = TestConstants.AuthorityOrganizationsTenant;
                publicClientID       = PublicCloudPublicClientIDOBO;
                confidentialClientID = PublicCloudConfidentialClientIDOBO;
                oboScope             = s_publicCloudOBOServiceScope;
                break;
            }

            //TODO: acquire scenario specific client ids from the lab response

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

            var msalPublicClient = PublicClientApplicationBuilder.Create(publicClientID)
                                   .WithAuthority(authority)
                                   .WithRedirectUri(TestConstants.RedirectUri)
                                   .WithTestLogging()
                                   .Build();

            var builder = msalPublicClient.AcquireTokenByUsernamePassword(oboScope, user.Upn, securePassword);

            builder.WithAuthority(authority);

            var authResult = await builder.ExecuteAsync().ConfigureAwait(false);

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(confidentialClientID)
                                  .WithAuthority(new Uri(oboHost + authResult.TenantId), true)
                                  .WithClientSecret(secret)
                                  .WithTestLogging()
                                  .Build();

            var userCacheRecorder = confidentialApp.UserTokenCache.RecordAccess();

            UserAssertion userAssertion = new UserAssertion(authResult.AccessToken);

            string atHash = userAssertion.AssertionHash;

            authResult = await confidentialApp.AcquireTokenOnBehalfOf(s_scopes, userAssertion)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult, user);
            Assert.AreEqual(atHash, userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);

#pragma warning disable CS0618 // Type or member is obsolete
            await confidentialApp.GetAccountsAsync().ConfigureAwait(false);

#pragma warning restore CS0618 // Type or member is obsolete
            Assert.IsNull(userCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
        }