Example #1
0
        public void AcquireTokenADFSV3InteractiveNonFederatedTest()
        {
            TestCommon.ResetInternalStaticCaches();

            _mobileTestHelper.AcquireTokenTestHelper(
                _xamarinController,
                LabUserHelper.GetAdfsUserAsync(FederationProvider.AdfsV4, false).GetAwaiter().GetResult(),
                CoreUiTestConstants.ADFSv3NonFederated);
        }
Example #2
0
        public void AcquireTokenSilentTest()
        {
            TestCommon.ResetInternalStaticCaches();

            _mobileTestHelper.AcquireTokenTestHelper(
                _xamarinController,
                LabUserHelper.GetDefaultUserAsync().GetAwaiter().GetResult(),
                CoreUiTestConstants.AcquireTokenSilent);
        }
Example #3
0
        public void B2CLocalAccountAcquireTokenTest()
        {
            TestCommon.ResetInternalStaticCaches();

            _mobileTestHelper.B2CLocalAccountAcquireTokenSilentTest(
                _xamarinController,
                LabUserHelper.GetB2CLocalAccountAsync().GetAwaiter().GetResult(),
                CoreUiTestConstants.B2CLocalb2clogin);
        }
        private void GetB2CClientIdFromLab()
        {
            if (_b2CClientId != null)
            {
                return;
            }
            LabResponse labResponse = LabUserHelper.GetB2CLocalAccount();

            _b2CClientId = labResponse.AppId;
        }
Example #5
0
        public void PerformB2CFacebookProviderSignInFlow(ITestController controller, LabUser user, UserInformationFieldIds userInformationFieldIds)
        {
            controller.Tap(CoreUiTestConstants.FacebookAccountID, XamarinSelector.ByHtmlIdAttribute);

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

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

            controller.Tap(userInformationFieldIds.SignInButtonId, XamarinSelector.ByHtmlIdAttribute);
        }
Example #6
0
 public void B2CFacebookMicrosoftLoginAcquireTokenTest()
 {
     TestCommon.ResetInternalStaticCaches();
     _mobileTestHelper.PerformB2CSelectProviderOnlyFlow(
         _xamarinController,
         LabUserHelper.GetB2CFacebookAccountAsync().GetAwaiter().GetResult().User,
         B2CIdentityProvider.Facebook,
         false);
     _mobileTestHelper.B2CSilentFlowHelper(_xamarinController);
 }
Example #7
0
        private async Task GetB2CClientIdFromLabAsync()
        {
            if (_b2CClientId != null)
            {
                return;
            }
            LabResponse labResponse = await LabUserHelper.GetB2CLocalAccountAsync().ConfigureAwait(false);

            _b2CClientId = labResponse.App.AppId;
        }
Example #8
0
        public async Task Interactive_SSHCert_Async()
        {
            LabResponse labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

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

            TokenCacheAccessRecorder userCacheAccess = pca.UserTokenCache.RecordAccess();

            Trace.WriteLine("Part 1 - Acquire an SSH cert interactively ");
            string jwk = CreateJwk();

            AuthenticationResult result = await pca
                                          .AcquireTokenInteractive(s_scopes)
                                          .WithCustomWebUi(CreateSeleniumCustomWebUI(labResponse.User, Prompt.ForceLogin))
                                          .WithSSHCertificateAuthenticationScheme(jwk, "key1")
                                          .WithExtraQueryParameters(GetTestSliceParams()) // TODO: remove this once feature is in PROD
                                          .ExecuteAsync(new CancellationTokenSource(_interactiveAuthTimeout).Token)
                                          .ConfigureAwait(false);

            userCacheAccess.AssertAccessCounts(0, 1);
            Assert.AreEqual("ssh-cert", result.TokenType);
            IAccount account = await MsalAssert.AssertSingleAccountAsync(labResponse, pca, result).ConfigureAwait(false);

            userCacheAccess.AssertAccessCounts(1, 1); // the assert calls GetAccounts

            Trace.WriteLine("Part 2 - Acquire a token silent with the same keyID - should be served from the cache");
            result = await pca
                     .AcquireTokenSilent(s_scopes, account)
                     .WithSSHCertificateAuthenticationScheme(jwk, "key1")
                     .WithExtraQueryParameters(GetTestSliceParams()) // TODO: remove this once feature is in PROD
                     .ExecuteAsync(new CancellationTokenSource(_interactiveAuthTimeout).Token)
                     .ConfigureAwait(false);

            userCacheAccess.AssertAccessCounts(2, 1);

            account = await MsalAssert.AssertSingleAccountAsync(labResponse, pca, result).ConfigureAwait(false);

            userCacheAccess.AssertAccessCounts(3, 1);

            Trace.WriteLine("Part 3 - Acquire a token silent with a different keyID - should not sbe served from the cache");
            result = await pca
                     .AcquireTokenSilent(s_scopes, account)
                     .WithSSHCertificateAuthenticationScheme(jwk, "key2")
                     .WithExtraQueryParameters(GetTestSliceParams()) // TODO: remove this once feature is in PROD
                     .ExecuteAsync(new CancellationTokenSource(_interactiveAuthTimeout).Token)
                     .ConfigureAwait(false);

            Assert.AreEqual("ssh-cert", result.TokenType);
            userCacheAccess.AssertAccessCounts(4, 2);
            await MsalAssert.AssertSingleAccountAsync(labResponse, pca, result).ConfigureAwait(false);
        }
        public async Task AcquireTokenWithManagedUsernameIncorrectPasswordAsync()
        {
            var labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

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

            await RunAcquireTokenWithUsernameIncorrectPasswordAsync(msalPublicClient, labResponse.User.Upn).ConfigureAwait(false);
        }
Example #10
0
        public void B2CLocalEditPolicyAcquireTokenTest()
        {
            TestCommon.ResetInternalStaticCaches();

            _mobileTestHelper.B2CLocalAccountAcquireTokenInteractiveTestHelper(
                _xamarinController,
                LabUserHelper.GetB2CLocalAccountAsync().GetAwaiter().GetResult(),
                CoreUiTestConstants.B2CLocalEditProfile);

            _mobileTestHelper.PerformB2CSignInEditProfileFlow(
                _xamarinController);
        }
        public async Task MultiUserCacheCompatabilityTestAsync()
        {
            // Arrange

            //Acquire AT for default lab account
            LabResponse labResponseDefault = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

            AuthenticationResult defaultAccountResult = await RunTestForUserAsync(labResponseDefault).ConfigureAwait(false);

            //Acquire AT for ADFS 2019 account
            LabResponse labResponseFederated = await LabUserHelper.GetAdfsUserAsync(FederationProvider.ADFSv2019, true).ConfigureAwait(false);

            var federatedAccountResult = await RunTestForUserAsync(labResponseFederated, false).ConfigureAwait(false);

            //Acquire AT for MSA account
            LabResponse labResponseMsa = await LabUserHelper.GetMsaUserAsync().ConfigureAwait(false);

            labResponseMsa.App.AppId = LabApiConstants.MSAOutlookAccountClientID;
            var msaAccountResult = await RunTestForUserAsync(labResponseMsa).ConfigureAwait(false);

            PublicClientApplication pca = PublicClientApplicationBuilder.Create(labResponseDefault.App.AppId).BuildConcrete();

            AuthenticationResult authResult = await pca.AcquireTokenSilent(new[] { CoreUiTestConstants.DefaultScope }, defaultAccountResult.Account)
                                              .ExecuteAsync()
                                              .ConfigureAwait(false);

            Assert.IsNotNull(authResult);
            Assert.IsNotNull(authResult.AccessToken);
            Assert.IsNotNull(authResult.IdToken);
            TestCommon.ValidateNoKerberosTicketFromAuthenticationResult(authResult);

            pca = PublicClientApplicationBuilder.Create(labResponseFederated.App.AppId).BuildConcrete();

            authResult = await pca.AcquireTokenSilent(new[] { CoreUiTestConstants.DefaultScope }, federatedAccountResult.Account)
                         .ExecuteAsync()
                         .ConfigureAwait(false);

            Assert.IsNotNull(authResult);
            Assert.IsNotNull(authResult.AccessToken);
            Assert.IsNull(authResult.IdToken);
            TestCommon.ValidateNoKerberosTicketFromAuthenticationResult(authResult);

            pca = PublicClientApplicationBuilder.Create(LabApiConstants.MSAOutlookAccountClientID).BuildConcrete();

            authResult = await pca.AcquireTokenSilent(new[] { CoreUiTestConstants.DefaultScope }, msaAccountResult.Account)
                         .ExecuteAsync()
                         .ConfigureAwait(false);

            Assert.IsNotNull(authResult);
            Assert.IsNotNull(authResult.AccessToken);
            Assert.IsNull(authResult.IdToken);
            TestCommon.ValidateNoKerberosTicketFromAuthenticationResult(authResult);
        }
Example #12
0
        public async Task Interactive_Arlington_MultiCloudSupport_AADAsync()
        {
            // Arrange
            LabResponse labResponse = await LabUserHelper.GetArlingtonUserAsync().ConfigureAwait(false);

            IPublicClientApplication pca = PublicClientApplicationBuilder
                                           .Create(labResponse.App.AppId)
                                           .WithRedirectUri(SeleniumWebUI.FindFreeLocalhostRedirectUri())
                                           .WithAuthority("https://login.microsoftonline.com/common")
                                           .WithMultiCloudSupport(true)
                                           .WithTestLogging()
                                           .Build();

            Trace.WriteLine("Part 1 - Acquire a token interactively");
            AuthenticationResult result = await pca
                                          .AcquireTokenInteractive(s_scopes)
                                          .WithCustomWebUi(CreateSeleniumCustomWebUI(labResponse.User, Prompt.SelectAccount, false))
                                          .ExecuteAsync(new CancellationTokenSource(_interactiveAuthTimeout).Token)
                                          .ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Account);
            Assert.IsNotNull(result.Account.GetTenantProfiles());
            Assert.IsTrue(result.Account.GetTenantProfiles().Any());
            Assert.AreEqual(labResponse.User.Upn, result.Account.Username);
            Assert.IsTrue(labResponse.Lab.Authority.Contains(result.Account.Environment));

            Trace.WriteLine("Part 2 - Get Accounts");
            var accounts = await pca.GetAccountsAsync().ConfigureAwait(false);

            Assert.IsNotNull(accounts);
            Assert.IsNotNull(accounts.Single());

            var account = accounts.Single();

            Assert.IsNotNull(account.GetTenantProfiles());
            Assert.IsTrue(account.GetTenantProfiles().Any());
            Assert.AreEqual(labResponse.User.Upn, account.Username);
            Assert.AreEqual("login.microsoftonline.us", account.Environment);

            Trace.WriteLine("Part 3 - Acquire a token silently");
            result = await pca
                     .AcquireTokenSilent(s_scopes, result.Account)
                     .ExecuteAsync(CancellationToken.None)
                     .ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Account);
            Assert.IsNotNull(result.Account.GetTenantProfiles());
            Assert.IsTrue(result.Account.GetTenantProfiles().Any());
            Assert.IsTrue(labResponse.Lab.Authority.Contains(result.Account.Environment));
        }
        public async Task SilentAuth_TokenCacheRemainsPersistent_Async()
        {
            var labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

            var    user          = labResponse.User;
            string cacheFilePath = null;

            try
            {
                cacheFilePath = Path.GetTempFileName();

                var pca1 = PublicClientApplicationBuilder
                           .Create(labResponse.App.AppId)
                           .WithTestLogging()
                           .WithAuthority("https://login.microsoftonline.com/organizations")
                           .Build();

                SetCacheSerializationToFile(pca1, cacheFilePath);

                AuthenticationResult authResult = await pca1
                                                  .AcquireTokenByUsernamePassword(s_scopes, user.Upn, new NetworkCredential("", user.GetOrFetchPassword()).SecurePassword)
                                                  .ExecuteAsync()
                                                  .ConfigureAwait(false);

                MsalAssert.AssertAuthResult(authResult, user);
                Assert.AreEqual(
                    "https://login.microsoftonline.com/organizations/oauth2/v2.0/token",
                    authResult.AuthenticationResultMetadata.TokenEndpoint);

                // simulate a restart by creating a new client
                var pca2 = PublicClientApplicationBuilder
                           .Create(labResponse.App.AppId)
                           .WithTestLogging()
                           .Build();

                SetCacheSerializationToFile(pca2, cacheFilePath);

                authResult = await pca2.AcquireTokenSilent(s_scopes, user.Upn)
                             .WithTenantId("organizations")
                             .ExecuteAsync()
                             .ConfigureAwait(false);

                MsalAssert.AssertAuthResult(authResult, user);
            }
            finally
            {
                if (cacheFilePath != null && File.Exists(cacheFilePath))
                {
                    File.Delete(cacheFilePath);
                }
            }
        }
Example #14
0
        public async Task AcquireTokenByObo_NormalOboThenLongRunningInitiate_WithTheSameKey_TestAsync()
        {
            var user1 = (await LabUserHelper.GetSpecificUserAsync("*****@*****.**").ConfigureAwait(false)).User;
            var pca   = PublicClientApplicationBuilder
                        .Create(PublicClientID)
                        .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
                        .Build();

            var userAuthResult = await pca
                                 .AcquireTokenByUsernamePassword(s_oboServiceScope, user1.Upn, new NetworkCredential("", user1.GetOrFetchPassword()).SecurePassword)
                                 .ExecuteAsync(CancellationToken.None)
                                 .ConfigureAwait(false);

            var cca = BuildCCA(userAuthResult.TenantId);

            UserAssertion userAssertion = new UserAssertion(userAuthResult.AccessToken);
            string        oboCacheKey   = userAssertion.AssertionHash;

            // AcquireNormal - AT from IdP via OBO flow(only new AT cached, no RT in cache)
            var result = await cca.AcquireTokenOnBehalfOf(s_scopes, userAssertion).ExecuteAsync().ConfigureAwait(false);

            Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);
            Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count);
            Assert.AreEqual(0, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count);

            // InitiateLR - AT from cache
            result = await cca.InitiateLongRunningProcessInWebApi(s_scopes, userAuthResult.AccessToken, ref oboCacheKey)
                     .ExecuteAsync().ConfigureAwait(false);

            Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource);

            // Expire AT
            TokenCacheHelper.ExpireAllAccessTokens(cca.UserTokenCacheInternal);

            // InitiateLR - AT via OBO flow (new AT, RT cached)
            result = await cca.InitiateLongRunningProcessInWebApi(s_scopes, userAuthResult.AccessToken, ref oboCacheKey)
                     .ExecuteAsync().ConfigureAwait(false);

            Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);
            Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count);
            Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count);

            // Expire AT
            TokenCacheHelper.ExpireAllAccessTokens(cca.UserTokenCacheInternal);

            // AcquireLR - AT from IdP via RT flow(new AT, RT cached)
            result = await cca.AcquireTokenInLongRunningProcess(s_scopes, oboCacheKey).ExecuteAsync().ConfigureAwait(false);

            Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);
            Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count);
            Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count);
        }
        public async Task OBO_WithCache_MultipleUsers_Async()
        {
            var aadUser1 = (await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false)).User;
            var aadUser2 = (await LabUserHelper.GetAdfsUserAsync(FederationProvider.AdfsV2, true).ConfigureAwait(false)).User;
            var adfsUser = (await LabUserHelper.GetAdfsUserAsync(FederationProvider.ADFSv2019).ConfigureAwait(false)).User;

            await RunOnBehalfOfTestAsync(adfsUser, false).ConfigureAwait(false);
            await RunOnBehalfOfTestAsync(aadUser1, false).ConfigureAwait(false);
            await RunOnBehalfOfTestAsync(aadUser1, true).ConfigureAwait(false);
            await RunOnBehalfOfTestAsync(aadUser2, false).ConfigureAwait(false);
            await RunOnBehalfOfTestAsync(adfsUser, true).ConfigureAwait(false);
            await RunOnBehalfOfTestAsync(aadUser2, true).ConfigureAwait(false);
        }
        public void AcquireTokenWithFederatedUsernameIncorrectPassword()
        {
            var user = LabUserHelper.GetDefaultUser().User;

            SecureString incorrectSecurePassword = new SecureString();

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

            PublicClientApplication msalPublicClient = new PublicClientApplication(ClientId, Authority);

            var result = Assert.ThrowsExceptionAsync <MsalException>(async() =>
                                                                     await msalPublicClient.AcquireTokenByUsernamePasswordAsync(Scopes, user.Upn, incorrectSecurePassword).ConfigureAwait(false));
        }
Example #17
0
        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 <MsalServiceException>(() =>
                                                                                      msalPublicClient
                                                                                      .AcquireTokenByUsernamePassword(s_scopes, labResponse.User.Upn, securePassword)
                                                                                      .ExecuteAsync(CancellationToken.None))
                         .ConfigureAwait(false);
        }
        public void PerformSignInFlow(ITestController controller, LabUser user)
        {
            UserInformationFieldIds userInformationFieldIds = DetermineUserInformationFieldIds(user);

            //Acquire token flow
            controller.Tap(CoreUiTestConstants.AcquireTokenID);

            //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.EnterText(userInformationFieldIds.PasswordInputId, LabUserHelper.GetUserPassword(user), XamarinSelector.ByHtmlIdAttribute);
            controller.Tap(userInformationFieldIds.SignInButtonId, XamarinSelector.ByHtmlIdAttribute);
        }
        public async Task AcquireTokenFromAdfsUsernamePasswordAsync()
        {
            LabResponse labResponse = await LabUserHelper.GetAdfsUserAsync(FederationProvider.ADFSv2019, true).ConfigureAwait(false);

            var user = labResponse.User;

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

            var msalPublicClient            = PublicClientApplicationBuilder.Create(Adfs2019LabConstants.PublicClientId).WithAdfsAuthority(Adfs2019LabConstants.Authority).Build();
            AuthenticationResult authResult = await msalPublicClient.AcquireTokenByUsernamePassword(s_scopes, user.Upn, securePassword).ExecuteAsync().ConfigureAwait(false);

            Assert.IsNotNull(authResult);
            Assert.IsNotNull(authResult.AccessToken);
            Assert.IsNotNull(authResult.IdToken);
        }
        public async Task Interactive_AdfsV3_FederatedAsync()
        {
            // Arrange
            UserQuery query = new UserQuery
            {
                FederationProvider = FederationProvider.AdfsV4,
                IsMamUser          = false,
                IsMfaUser          = false,
                IsFederatedUser    = true
            };

            LabResponse labResponse = await LabUserHelper.GetLabUserDataAsync(query).ConfigureAwait(false);

            await RunTestForUserAsync(labResponse).ConfigureAwait(false);
        }
Example #21
0
        public async Task OboAndClient_WithRegional_TestAsync()
        {
            // Setup: Get lab user, create PCA and get user tokens
            var user = (await LabUserHelper.GetSpecificUserAsync("*****@*****.**").ConfigureAwait(false)).User;

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

            var userResult = await pca
                             .AcquireTokenByUsernamePassword(s_oboServiceScope, user.Upn, new NetworkCredential("", user.GetOrFetchPassword()).SecurePassword)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

            // Act and Assert different scenarios
            var cca = BuildCCA(userResult.TenantId, true);

            // OBO uses global - IdP
            var oboResult = await cca.AcquireTokenOnBehalfOf(s_scopes, new UserAssertion(userResult.AccessToken))
                            .ExecuteAsync(CancellationToken.None)
                            .ConfigureAwait(false);

            Assert.AreEqual(TokenSource.IdentityProvider, oboResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsFalse(oboResult.AuthenticationResultMetadata.TokenEndpoint.Contains(TestConstants.Region));

            // Client uses regional - IdP
            var clientResult = await cca.AcquireTokenForClient(new string[] { "https://graph.microsoft.com/.default" })
                               .ExecuteAsync(CancellationToken.None)
                               .ConfigureAwait(false);

            Assert.AreEqual(TokenSource.IdentityProvider, clientResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsTrue(clientResult.AuthenticationResultMetadata.TokenEndpoint.Contains(TestConstants.Region));

            // OBO from cache
            oboResult = await cca.AcquireTokenOnBehalfOf(s_scopes, new UserAssertion(userResult.AccessToken))
                        .ExecuteAsync(CancellationToken.None)
                        .ConfigureAwait(false);

            Assert.AreEqual(TokenSource.Cache, oboResult.AuthenticationResultMetadata.TokenSource);

            // Client from cache
            clientResult = await cca.AcquireTokenForClient(new string[] { "https://graph.microsoft.com/.default" })
                           .ExecuteAsync(CancellationToken.None)
                           .ConfigureAwait(false);

            Assert.AreEqual(TokenSource.Cache, clientResult.AuthenticationResultMetadata.TokenSource);
        }
Example #22
0
        public async Task SilentAuth_ForceRefresh_Async()
        {
            var labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

            var user = labResponse.User;

            var pca = PublicClientApplicationBuilder
                      .Create(labResponse.App.AppId)
                      .WithAuthority("https://login.microsoftonline.com/organizations")
                      .Build();

            Trace.WriteLine("Part 1 - Acquire a token with U/P");
            AuthenticationResult authResult = await pca
                                              .AcquireTokenByUsernamePassword(s_scopes, user.Upn, new NetworkCredential("", user.GetOrFetchPassword()).SecurePassword)
                                              .ExecuteAsync(new CancellationTokenSource().Token)
                                              .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult, user);
            var at1 = authResult.AccessToken;

            // If test fails with "user needs to consent to the application, do an interactive request" error - see UsernamePassword tests

            Trace.WriteLine("Part 2 - Acquire a token silently, with forceRefresh = true");
            IAccount account = await MsalAssert.AssertSingleAccountAsync(labResponse, pca, authResult).ConfigureAwait(false);

            authResult = await pca.AcquireTokenSilent(s_scopes, account)
                         .WithForceRefresh(true)
                         .ExecuteAsync()
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult, user);
            var at2 = authResult.AccessToken;

            Trace.WriteLine("Part 3 - Acquire a token silently with a login hint, with forceRefresh = true");
            authResult = await pca.AcquireTokenSilent(s_scopes, user.Upn)
                         .WithForceRefresh(true)
                         .ExecuteAsync()
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult, user);
            var at3 = authResult.AccessToken;

            Assert.IsFalse(at1.Equals(at2, System.StringComparison.InvariantCultureIgnoreCase));
            Assert.IsFalse(at1.Equals(at3, System.StringComparison.InvariantCultureIgnoreCase));
            Assert.IsFalse(at2.Equals(at3, System.StringComparison.InvariantCultureIgnoreCase));
        }
Example #23
0
        public async Task GetTokenByAuthCode_HybridSPA_Async()
        {
            // Arrange
            LabResponse labResponse = await LabUserHelper.GetHybridSpaAccontAsync().ConfigureAwait(false);

            var result = await RunTestForUserAsync(labResponse.App.AppId, labResponse,
                                                   "https://login.microsoftonline.com/f645ad92-e38d-4d1a-b510-d1b09a74a8ca", false,
                                                   "http://localhost:3000/auth/implicit-redirect").ConfigureAwait(false);

            Assert.IsNotNull(result.SpaAuthCode);

            result = await RunTestForUserAsync(labResponse.App.AppId, labResponse,
                                               "https://login.microsoftonline.com/f645ad92-e38d-4d1a-b510-d1b09a74a8ca", false,
                                               "http://localhost:3000/auth/implicit-redirect", false).ConfigureAwait(false);

            Assert.IsNull(result.SpaAuthCode);
        }
Example #24
0
        public void TestInitialize()
        {
            if (user == null)
            {
                user = LabUserHelper.GetDefaultUser().User;

                string stringPassword = LabUserHelper.GetUserPassword(user);
                securePassword = new NetworkCredential("", stringPassword).SecurePassword;
                authority      = string.Format(
                    CultureInfo.InvariantCulture,
                    AuthorityTemplate,
                    user.CurrentTenantId);
            }

            InitAdal();
            InitMsal();
        }
Example #25
0
        public async Task SilentAuth_ForceRefresh_Async()
        {
            var labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

            pca = PublicClientApplicationBuilder
                  .Create(labResponse.App.AppId)
                  .WithAuthority("https://login.microsoftonline.com/organizations")
                  .Build();

            Trace.WriteLine("Part 1 - Acquire a token with U/P");
            AuthenticationResult authResult = await pca
                                              .AcquireTokenByUsernamePassword(s_scopes, labResponse.User.Upn, new NetworkCredential("", labResponse.User.GetOrFetchPassword()).SecurePassword)
                                              .ExecuteAsync(new CancellationTokenSource().Token)
                                              .ConfigureAwait(false);

            await ValidateAuthResultAsync(authResult, labResponse).ConfigureAwait(false);
        }
Example #26
0
        [Timeout(1 * 60 * 1000)] // 1 min timeout
        public async Task DeviceCodeFlowTestAsync()
        {
            LabResponse labResponse = LabUserHelper.GetDefaultUser();

            Trace.WriteLine("Calling AcquireTokenWithDeviceCodeAsync");
            PublicClientApplication pca = new PublicClientApplication(labResponse.AppId);
            var result = await pca.AcquireTokenWithDeviceCodeAsync(Scopes, deviceCodeResult =>
            {
                RunAutomatedDeviceCodeFlow(deviceCodeResult, labResponse.User);

                return(Task.FromResult(0));
            }).ConfigureAwait(false);

            Trace.WriteLine("Running asserts");

            Assert.IsNotNull(result);
            Assert.IsTrue(!string.IsNullOrEmpty(result.AccessToken));
        }
        [Timeout(1 * 60 * 1000)] // 1 min timeout
        public async Task DeviceCodeFlowTestAsync()
        {
            LabResponse labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

            Trace.WriteLine("Calling AcquireTokenWithDeviceCodeAsync");
            var pca    = PublicClientApplicationBuilder.Create(labResponse.AppId).Build();
            var result = await pca.AcquireTokenWithDeviceCode(s_scopes, deviceCodeResult =>
            {
                RunAutomatedDeviceCodeFlow(deviceCodeResult, labResponse.User);

                return(Task.FromResult(0));
            }).ExecuteAsync(CancellationToken.None).ConfigureAwait(false);

            Trace.WriteLine("Running asserts");

            Assert.IsNotNull(result);
            Assert.IsTrue(!string.IsNullOrEmpty(result.AccessToken));
        }
Example #28
0
        public async Task AcquireTokenByObo_LongRunningAndNormalObo_WithDifferentKeys_TestAsync()
        {
            var user1 = (await LabUserHelper.GetSpecificUserAsync("*****@*****.**").ConfigureAwait(false)).User;
            var pca   = PublicClientApplicationBuilder
                        .Create(PublicClientID)
                        .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
                        .Build();

            var userAuthResult = await pca
                                 .AcquireTokenByUsernamePassword(s_oboServiceScope, user1.Upn, new NetworkCredential("", user1.GetOrFetchPassword()).SecurePassword)
                                 .ExecuteAsync(CancellationToken.None)
                                 .ConfigureAwait(false);

            var cca = BuildCCA(userAuthResult.TenantId);

            string        oboCacheKey   = "obo-cache-key";
            UserAssertion userAssertion = new UserAssertion(userAuthResult.AccessToken);

            var result = await cca.InitiateLongRunningProcessInWebApi(s_scopes, userAuthResult.AccessToken, ref oboCacheKey)
                         .ExecuteAsync().ConfigureAwait(false);

            // Cache has 1 partition (user-provided key) with 1 token
            Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);
            Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count);
            Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count);

            result = await cca.AcquireTokenOnBehalfOf(s_scopes, userAssertion).ExecuteAsync().ConfigureAwait(false);

            // Cache has 2 partitions (user-provided key, assertion) with 1 token each
            Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);
            Assert.AreEqual(2, cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count);
            Assert.AreEqual(1, cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count);

            // Returns long-running token
            result = await cca.AcquireTokenInLongRunningProcess(s_scopes, oboCacheKey).ExecuteAsync().ConfigureAwait(false);

            Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource);

            // Returns normal token
            result = await cca.AcquireTokenOnBehalfOf(s_scopes, userAssertion).ExecuteAsync().ConfigureAwait(false);

            Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource);
        }
Example #29
0
        private static async Task<AuthenticationResult> AcquireTokenForLabUserAsync()
        {
            var labResponse = await LabUserHelper.GetSpecificUserAsync(TestConstants.OBOUser).ConfigureAwait(false);
            var msalPublicClient = PublicClientApplicationBuilder
               .Create(TestConstants.OBOClientSideClientId)
               .WithAuthority(labResponse.Lab.Authority, TestConstants.Organizations)
               .Build();

            AuthenticationResult authResult = await msalPublicClient
                .AcquireTokenByUsernamePassword(
                TestConstants.OBOApiScope,
                TestConstants.OBOUser,
                new NetworkCredential(
                    TestConstants.OBOUser,
                    labResponse.User.GetOrFetchPassword()).SecurePassword)
                .ExecuteAsync(CancellationToken.None)
                .ConfigureAwait(false);

            return authResult;
        }
Example #30
0
        [Timeout(2 * 60 * 1000)] // 2 min timeout
        public async Task DeviceCodeFlowTestAsync()
        {
            LabResponse labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

            Trace.WriteLine("Calling AcquireTokenWithDeviceCodeAsync");
            var pca             = PublicClientApplicationBuilder.Create(labResponse.AppId).Build();
            var userCacheAccess = pca.UserTokenCache.RecordAccess();

            var result = await pca.AcquireTokenWithDeviceCode(s_scopes, deviceCodeResult =>
            {
                SeleniumExtensions.PerformDeviceCodeLogin(deviceCodeResult, labResponse.User, TestContext, false);
                return(Task.FromResult(0));
            }).ExecuteAsync(CancellationToken.None).ConfigureAwait(false);

            Trace.WriteLine("Running asserts");

            userCacheAccess.AssertAccessCounts(0, 1);
            Assert.IsNotNull(result);
            Assert.IsTrue(!string.IsNullOrEmpty(result.AccessToken));
        }