Ejemplo n.º 1
0
        public async Task RunTestWithClientSecretAsync(string clientID, string authority, string secret)
        {
            var confidentialClientAuthority = authority;

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(clientID)
                                  .WithAuthority(new Uri(confidentialClientAuthority), true)
                                  .WithClientSecret(secret)
                                  .Build();
            var appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess();

            var authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(1, 1);
            Assert.IsTrue(appCacheRecorder.LastNotificationArgs.IsApplicationCache);

            // Call again to ensure token cache is hit
            authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(2, 1);
            Assert.IsTrue(appCacheRecorder.LastNotificationArgs.IsApplicationCache);
        }
Ejemplo n.º 2
0
        private async Task RunPromptTestForUserAsync(LabResponse labResponse, Prompt prompt, bool useLoginHint)
        {
            var pca = PublicClientApplicationBuilder
                      .Create(labResponse.App.AppId)
                      .WithDefaultRedirectUri()
                      .WithRedirectUri(SeleniumWebUI.FindFreeLocalhostRedirectUri())
                      .WithTestLogging()
                      .Build();

            AcquireTokenInteractiveParameterBuilder builder = pca
                                                              .AcquireTokenInteractive(s_scopes)
                                                              .WithPrompt(prompt)
                                                              .WithCustomWebUi(CreateSeleniumCustomWebUI(labResponse.User, prompt, useLoginHint));

            if (useLoginHint)
            {
                builder = builder.WithLoginHint(labResponse.User.Upn);
            }

            AuthenticationResult result = await builder
                                          .ExecuteAsync(new CancellationTokenSource(_interactiveAuthTimeout).Token)
                                          .ConfigureAwait(false);

            await MsalAssert.AssertSingleAccountAsync(labResponse, pca, result).ConfigureAwait(false);
        }
Ejemplo n.º 3
0
        public async Task RunTestWithClientSecretAsync(string clientID, string authority, string secret)
        {
            var confidentialClientAuthority = authority;

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(clientID)
                                  .WithAuthority(new Uri(confidentialClientAuthority), true)
                                  .WithClientSecret(secret)
                                  .WithTestLogging()
                                  .Build();
            var appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess();

            var authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(1, 1);
            Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.AreEqual(clientID + "_AppTokenCache", appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);

            // Call again to ensure token cache is hit
            authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(2, 1);
            Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.AreEqual(clientID + "_AppTokenCache", appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
        }
Ejemplo n.º 4
0
        public async Task ConfidentialClientWithRSACertificateTestAsync()
        {
            AuthenticationResult           authResult;
            IConfidentialClientApplication confidentialApp;
            X509Certificate2 cert           = GetCertificate(true);
            var confidentialClientAuthority = PublicCloudTestAuthority;

            confidentialApp = ConfidentialClientApplicationBuilder
                              .Create(PublicCloudConfidentialClientID)
                              .WithAuthority(new Uri(confidentialClientAuthority), true)
                              .WithCertificate(cert)
                              .Build();
            var appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess();

            authResult = await confidentialApp
                         .AcquireTokenForClient(s_keyvaultScope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(1, 1);
            Assert.IsTrue(appCacheRecorder.LastNotificationArgs.IsApplicationCache);

            // Call again to ensure token cache is hit
            authResult = await confidentialApp
                         .AcquireTokenForClient(s_keyvaultScope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(2, 1);
            Assert.IsTrue(appCacheRecorder.LastNotificationArgs.IsApplicationCache);
        }
Ejemplo n.º 5
0
        public async Task ConfidentialClientWithDefaultClaimsTestAsync()
        {
            var keyvault = new KeyVaultSecretsProvider();
            var secret   = keyvault.GetSecret(TestConstants.MsalCCAKeyVaultUri).Value;
            var confidentialClientAuthority = "https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47";
            var claims = GetClaims(false);

            X509Certificate2 cert = GetCertificate();

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(ConfidentialClientID)
                                  .WithAuthority(new Uri(confidentialClientAuthority), true)
                                  .WithClientClaims(cert, claims)
                                  .Build();

            var authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

            var handler   = new JwtSecurityTokenHandler();
            var jsonToken = handler.ReadJwtToken(((ConfidentialClientApplication)confidentialApp).ClientCredential.CachedAssertion);

            //checked if additional claim is in signed assertion
            var validClaim = claims.Where(x => x.Key == jsonToken.Claims.FirstOrDefault().Type&& x.Value == jsonToken.Claims.FirstOrDefault().Value).FirstOrDefault();

            Assert.IsNotNull(validClaim);

            MsalAssert.AssertAuthResult(authResult);
        }
Ejemplo n.º 6
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);
        }
        private async Task RunOnBehalfOfTestAsync(LabResponse labResponse)
        {
            var user = labResponse.User;

            var keyvault = new KeyVaultSecretsProvider();
            var secret   = keyvault.GetSecret(MsalTestConstants.MsalOBOKeyVaultUri).Value;
            //TODO: acquire scenario specific client ids from the lab resonse
            var publicClientID          = "be9b0186-7dfd-448a-a944-f771029105bf";
            var oboConfidentialClientID = "23c64cd8-21e4-41dd-9756-ab9e2c23f58c";

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

            var msalPublicClient = PublicClientApplicationBuilder.Create(publicClientID).WithAuthority(MsalTestConstants.AuthorityOrganizationsTenant).WithRedirectUri("urn:ietf:wg:oauth:2.0:oob").Build();

            AuthenticationResult authResult = await msalPublicClient
                                              .AcquireTokenByUsernamePassword(s_oboServiceScope, user.Upn, securePassword)
                                              .ExecuteAsync(CancellationToken.None)
                                              .ConfigureAwait(false);

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(oboConfidentialClientID)
                                  .WithAuthority(new Uri("https://login.microsoftonline.com/" + 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);
        }
Ejemplo n.º 8
0
        public async Task ConfidentialClientWithSignedAssertionTestAsync()
        {
            var confidentialClientAuthority = PublicCloudTestAuthority;
            var claims = GetClaims();

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(PublicCloudConfidentialClientID)
                                  .WithAuthority(new Uri(confidentialClientAuthority), true)
                                  .WithClientAssertion(GetSignedClientAssertionUsingMsalInternal(PublicCloudConfidentialClientID, claims))
                                  .Build();

            var appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess();

            var authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

            appCacheRecorder.AssertAccessCounts(1, 1);
            Assert.IsTrue(appCacheRecorder.LastNotificationArgs.IsApplicationCache);
            ValidateClaimsInAssertion(claims, ((ConfidentialClientApplication)confidentialApp).ClientCredential.SignedAssertion);
            MsalAssert.AssertAuthResult(authResult);

            // call again to ensure cache is hit
            authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            appCacheRecorder.AssertAccessCounts(2, 1);
            Assert.IsTrue(appCacheRecorder.LastNotificationArgs.IsApplicationCache);
        }
Ejemplo n.º 9
0
        public async Task ConfidentialClientWithSignedAssertionTestAsync()
        {
            var keyvault = new KeyVaultSecretsProvider();
            var confidentialClientAuthority = "https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47";
            var claims = GetClaims();

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(ConfidentialClientID)
                                  .WithAuthority(new Uri(confidentialClientAuthority), true)
                                  .WithClientAssertion(GetSignedClientAssertion(ConfidentialClientID, claims))
                                  .Build();

            var appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess();

            var authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

            appCacheRecorder.AssertAccessCounts(1, 1);
            Assert.IsTrue(appCacheRecorder.LastNotificationArgs.IsApplicationCache);
            ValidateClaimsInAssertion(claims, ((ConfidentialClientApplication)confidentialApp).ClientCredential.SignedAssertion);
            MsalAssert.AssertAuthResult(authResult);

            // call again to ensure cache is hit
            authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            appCacheRecorder.AssertAccessCounts(2, 1);
            Assert.IsTrue(appCacheRecorder.LastNotificationArgs.IsApplicationCache);
        }
        public async Task ConfidentialClientWithCertificateTestAsync()
        {
            AuthenticationResult           authResult;
            IConfidentialClientApplication confidentialApp;
            X509Certificate2 cert;
            var confidentialClientAuthority = "https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47";

            cert = CertificateHelper.FindCertificateByThumbprint("79fbcbeb5cd28994e50daff8035bacf764b14306");
            if (cert == null)
            {
                throw new InvalidOperationException(
                          "Test setup error - cannot find a certificate in the My store for KeyVault. This is available for Microsoft employees only.");
            }

            confidentialApp = ConfidentialClientApplicationBuilder
                              .Create(ConfidentialClientID)
                              .WithAuthority(new Uri(confidentialClientAuthority), true)
                              .WithCertificate(cert)
                              .Build();

            authResult = await confidentialApp
                         .AcquireTokenForClient(s_keyvaultScope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
        }
Ejemplo n.º 11
0
        public async Task ConfidentialClientWithClientSecretTestAsync()
        {
            var keyvault = new KeyVaultSecretsProvider();
            var secret   = keyvault.GetSecret(TestConstants.MsalCCAKeyVaultUri).Value;
            var confidentialClientAuthority = "https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47";

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(ConfidentialClientID)
                                  .WithAuthority(new Uri(confidentialClientAuthority), true)
                                  .WithClientSecret(secret)
                                  .Build();
            var appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess();

            var authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(1, 1);
            Assert.IsTrue(appCacheRecorder.LastNotificationArgs.IsApplicationCache);

            // Call again to ensure token cache is hit
            authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(2, 1);
            Assert.IsTrue(appCacheRecorder.LastNotificationArgs.IsApplicationCache);
        }
Ejemplo n.º 12
0
        public async Task ConfidentialClientWithDefaultClaimsTestAsync()
        {
            var confidentialClientAuthority = PublicCloudTestAuthority;
            var claims = GetClaims(false);

            X509Certificate2 cert = GetCertificate();

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(PublicCloudConfidentialClientID)
                                  .WithAuthority(new Uri(confidentialClientAuthority), true)
                                  .WithClientClaims(cert, claims)
                                  .Build();

            var authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

            var handler   = new JwtSecurityTokenHandler();
            var jsonToken = handler.ReadJwtToken(((ConfidentialClientApplication)confidentialApp).ClientCredential.CachedAssertion);

            //checked if additional claim is in signed assertion
            var validClaim = claims.Where(x => x.Key == jsonToken.Claims.FirstOrDefault().Type&& x.Value == jsonToken.Claims.FirstOrDefault().Value).FirstOrDefault();

            Assert.IsNotNull(validClaim);

            MsalAssert.AssertAuthResult(authResult);
        }
        private async Task ValidateAuthResultAsync(
            AuthenticationResult authResult,
            LabResponse labResponse)
        {
            MsalAssert.AssertAuthResult(authResult, labResponse.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, labResponse.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, labResponse.User.Upn)
                         .WithForceRefresh(true)
                         .ExecuteAsync()
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult, labResponse.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));
            Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
        }
Ejemplo n.º 14
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);
        }
        private async Task <AuthenticationResult> RunTestForUserAsync(LabResponse labResponse, bool directToAdfs = false)
        {
            IPublicClientApplication pca;

            if (directToAdfs)
            {
                pca = PublicClientApplicationBuilder
                      .Create(Adfs2019LabConstants.PublicClientId)
                      .WithRedirectUri(Adfs2019LabConstants.ClientRedirectUri)
                      .WithAdfsAuthority(Adfs2019LabConstants.Authority)
                      .BuildConcrete();
            }
            else
            {
                pca = PublicClientApplicationBuilder
                      .Create(labResponse.AppId)
                      .WithRedirectUri(SeleniumWebUI.FindFreeLocalhostRedirectUri())
                      .Build();
            }
            Trace.WriteLine("Part 1 - Acquire a token interactively, no login hint");
            AuthenticationResult result = await pca
                                          .AcquireTokenInteractive(s_scopes)
                                          .WithCustomWebUi(CreateSeleniumCustomWebUI(labResponse.User, Prompt.SelectAccount, false, directToAdfs))
                                          .ExecuteAsync(new CancellationTokenSource(_interactiveAuthTimeout).Token)
                                          .ConfigureAwait(false);

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

            Trace.WriteLine("Part 2 - Clear the cache");
            await pca.RemoveAsync(account).ConfigureAwait(false);

            Assert.IsFalse((await pca.GetAccountsAsync().ConfigureAwait(false)).Any());

            Trace.WriteLine("Part 3 - Acquire a token interactively again, with login hint");
            result = await pca
                     .AcquireTokenInteractive(s_scopes)
                     .WithCustomWebUi(CreateSeleniumCustomWebUI(labResponse.User, Prompt.ForceLogin, true, directToAdfs))
                     .WithPrompt(Prompt.ForceLogin)
                     .WithLoginHint(labResponse.User.HomeUPN)
                     .ExecuteAsync(new CancellationTokenSource(_interactiveAuthTimeout).Token)
                     .ConfigureAwait(false);

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

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

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

            return(result);
        }
Ejemplo n.º 16
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 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);
                }
            }
        }
Ejemplo n.º 18
0
        private async Task RunClientCredsAsync(Cloud cloud, CredentialType credentialType, bool UseAppIdUri = false, bool sendX5C = false)
        {
            Trace.WriteLine($"Running test with settings for cloud {cloud}, credential type {credentialType}");
            IConfidentialAppSettings settings = ConfidentialAppSettings.GetSettings(cloud);

            settings.UseAppIdUri = UseAppIdUri;

            AuthenticationResult authResult;

            IConfidentialClientApplication confidentialApp = CreateApp(credentialType, settings, sendX5C);
            var  appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess();
            Guid correlationId    = Guid.NewGuid();

            authResult = await confidentialApp
                         .AcquireTokenForClient(settings.AppScopes)
                         .WithCorrelationId(correlationId)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(1, 1);
            Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
            Assert.AreEqual(correlationId, appCacheRecorder.LastAfterAccessNotificationArgs.CorrelationId);
            Assert.AreEqual(correlationId, appCacheRecorder.LastBeforeAccessNotificationArgs.CorrelationId);
            Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationTotalInMs > 0);
            Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationInHttpInMs > 0);
            Assert.AreEqual(
                GetExpectedCacheKey(settings.ClientId, settings.TenantId),
                appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);

            // Call again to ensure token cache is hit
            authResult = await confidentialApp
                         .AcquireTokenForClient(settings.AppScopes)
                         .ExecuteAsync()
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationInHttpInMs == 0);

            appCacheRecorder.AssertAccessCounts(2, 1);
            Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
            Assert.AreNotEqual(correlationId, appCacheRecorder.LastAfterAccessNotificationArgs.CorrelationId);
            Assert.AreNotEqual(correlationId, appCacheRecorder.LastBeforeAccessNotificationArgs.CorrelationId);
            Assert.AreEqual(
                GetExpectedCacheKey(settings.ClientId, settings.TenantId),
                appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
        }
Ejemplo n.º 19
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));
        }
        public async Task ConfidentialClientWithClientSecretTestAsync()
        {
            var keyvault = new KeyVaultSecretsProvider();
            var secret   = keyvault.GetSecret(MsalTestConstants.MsalCCAKeyVaultUri).Value;
            var confidentialClientAuthority = "https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47";

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(ConfidentialClientID)
                                  .WithAuthority(new Uri(confidentialClientAuthority), true)
                                  .WithClientSecret(secret)
                                  .Build();

            var authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
        }
Ejemplo n.º 21
0
        public async Task ConfidentialClientWithCertificateTestAsync()
        {
            AuthenticationResult           authResult;
            IConfidentialClientApplication confidentialApp;
            X509Certificate2 cert           = GetCertificate();
            var confidentialClientAuthority = PublicCloudTestAuthority;

            confidentialApp = ConfidentialClientApplicationBuilder
                              .Create(PublicCloudConfidentialClientID)
                              .WithAuthority(new Uri(confidentialClientAuthority), true)
                              .WithCertificate(cert)
                              .WithTestLogging()
                              .Build();

            var appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess();

            authResult = await confidentialApp
                         .AcquireTokenForClient(s_keyvaultScope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(1, 1);
            Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
            Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationTotalInMs > 0);
            Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationInHttpInMs > 0);

            // Call again to ensure token cache is hit
            authResult = await confidentialApp
                         .AcquireTokenForClient(s_keyvaultScope)
                         .ExecuteAsync()
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationTotalInMs > 0);
            Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationInHttpInMs == 0);

            appCacheRecorder.AssertAccessCounts(2, 1);
            Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
        }
Ejemplo n.º 22
0
        public async Task ConfidentialClientWithRSACertificateTestAsync()
        {
            AuthenticationResult           authResult;
            IConfidentialClientApplication confidentialApp;
            X509Certificate2 cert = GetCertificate(true);

            confidentialApp = ConfidentialClientApplicationBuilder
                              .Create(PublicCloudConfidentialClientID)
                              .WithAuthority(PublicCloudTestAuthority)
                              .WithCertificate(cert)
                              .Build();
            var appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess();

            authResult = await confidentialApp
                         .AcquireTokenForClient(s_keyvaultScope)
                         .WithAuthority(PublicCloudTestAuthority, true)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(1, 1);
            Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.AreEqual(
                GetExpectedCacheKey(PublicCloudConfidentialClientID, Authority.CreateAuthority(PublicCloudTestAuthority, false).TenantId),
                appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);

            // Call again to ensure token cache is hit
            authResult = await confidentialApp
                         .AcquireTokenForClient(s_keyvaultScope)
                         .WithAuthority(PublicCloudTestAuthority, true)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(2, 1);
            Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.AreEqual(
                GetExpectedCacheKey(PublicCloudConfidentialClientID, Authority.CreateAuthority(PublicCloudTestAuthority, false).TenantId),
                appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
        }
Ejemplo n.º 23
0
        public async Task ConfidentialClientWithRSACertificateTestAsync()
        {
            AuthenticationResult           authResult;
            IConfidentialClientApplication confidentialApp;
            X509Certificate2 cert           = GetCertificate(true);
            var confidentialClientAuthority = "https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47";

            confidentialApp = ConfidentialClientApplicationBuilder
                              .Create(ConfidentialClientID)
                              .WithAuthority(new Uri(confidentialClientAuthority), true)
                              .WithCertificate(cert)
                              .Build();

            authResult = await confidentialApp
                         .AcquireTokenForClient(s_keyvaultScope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
        }
Ejemplo n.º 24
0
        public async Task ConfidentialClientWithNoDefaultClaimsTestAsync()
        {
            var confidentialClientAuthority = PublicCloudTestAuthority;
            var claims = GetClaims();

            X509Certificate2 cert = GetCertificate();

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(PublicCloudConfidentialClientID)
                                  .WithAuthority(new Uri(confidentialClientAuthority), true)
                                  .WithClientClaims(cert, claims, false)
                                  .Build();

            var authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

            ValidateClaimsInAssertion(claims, ((ConfidentialClientApplication)confidentialApp).ClientCredential.CachedAssertion);

            MsalAssert.AssertAuthResult(authResult);
        }
Ejemplo n.º 25
0
        public async Task ConfidentialClientWithNoDefaultClaimsTestAsync()
        {
            var keyvault = new KeyVaultSecretsProvider();
            var confidentialClientAuthority = "https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47";
            var claims = GetClaims();

            X509Certificate2 cert = GetCertificate();

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(ConfidentialClientID)
                                  .WithAuthority(new Uri(confidentialClientAuthority), true)
                                  .WithClientClaims(cert, claims, false)
                                  .Build();

            var authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

            ValidateClaimsInAssertion(claims, ((ConfidentialClientApplication)confidentialApp).ClientCredential.CachedAssertion);

            MsalAssert.AssertAuthResult(authResult);
        }
Ejemplo n.º 26
0
        public async Task ConfidentialClientWithSignedAssertionTestAsync()
        {
            var confidentialClientAuthority = PublicCloudTestAuthority;
            var claims = GetClaims();

            var confidentialApp = ConfidentialClientApplicationBuilder
                                  .Create(PublicCloudConfidentialClientID)
                                  .WithAuthority(new Uri(confidentialClientAuthority), true)
                                  .WithClientAssertion(GetSignedClientAssertionUsingMsalInternal(PublicCloudConfidentialClientID, claims))
                                  .WithTestLogging()
                                  .Build();

            var appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess();

            var authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                             .ExecuteAsync(CancellationToken.None)
                             .ConfigureAwait(false);

            appCacheRecorder.AssertAccessCounts(1, 1);
            Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.AreEqual(
                GetExpectedCacheKey(PublicCloudConfidentialClientID, Authority.CreateAuthority(confidentialClientAuthority, false).TenantId),
                appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            ValidateClaimsInAssertion(claims, ((ConfidentialClientApplication)confidentialApp).ClientCredential.SignedAssertion);
            MsalAssert.AssertAuthResult(authResult);

            // call again to ensure cache is hit
            authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            appCacheRecorder.AssertAccessCounts(2, 1);
            Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.AreEqual(
                GetExpectedCacheKey(PublicCloudConfidentialClientID, Authority.CreateAuthority(confidentialClientAuthority, false).TenantId),
                appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
        }
Ejemplo n.º 27
0
        private async Task <AuthenticationResult> RunTestForUserAsync(LabResponse labResponse, bool directToAdfs = false)
        {
            HttpSnifferClientFactory factory = null;
            IPublicClientApplication pca;

            if (directToAdfs)
            {
                pca = PublicClientApplicationBuilder
                      .Create(Adfs2019LabConstants.PublicClientId)
                      .WithRedirectUri(Adfs2019LabConstants.ClientRedirectUri)
                      .WithAdfsAuthority(Adfs2019LabConstants.Authority)
                      .WithTestLogging()
                      .Build();
            }
            else
            {
                pca = PublicClientApplicationBuilder
                      .Create(labResponse.App.AppId)
                      .WithRedirectUri(SeleniumWebUI.FindFreeLocalhostRedirectUri())
                      .WithAuthority(labResponse.Lab.Authority + "common")
                      .WithTestLogging(out factory)
                      .Build();
            }

            var userCacheAccess = pca.UserTokenCache.RecordAccess();

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

            Assert.IsTrue(result.AuthenticationResultMetadata.DurationTotalInMs > 0);
            Assert.IsTrue(result.AuthenticationResultMetadata.DurationInHttpInMs > 0);

            userCacheAccess.AssertAccessCounts(0, 1);
            IAccount account = await MsalAssert.AssertSingleAccountAsync(labResponse, pca, result).ConfigureAwait(false);

            userCacheAccess.AssertAccessCounts(1, 1); // the assert calls GetAccounts
            Assert.IsFalse(userCacheAccess.LastAfterAccessNotificationArgs.IsApplicationCache);

            Trace.WriteLine("Part 2 - Clear the cache");
            await pca.RemoveAsync(account).ConfigureAwait(false);

            userCacheAccess.AssertAccessCounts(1, 2);
            Assert.IsFalse((await pca.GetAccountsAsync().ConfigureAwait(false)).Any());
            userCacheAccess.AssertAccessCounts(2, 2);
            Assert.IsFalse(userCacheAccess.LastAfterAccessNotificationArgs.IsApplicationCache);

            if (factory?.RequestsAndResponses != null)
            {
                factory.RequestsAndResponses.Clear();
            }

            Trace.WriteLine("Part 3 - Acquire a token interactively again, with login hint");
            result = await pca
                     .AcquireTokenInteractive(s_scopes)
                     .WithCustomWebUi(CreateSeleniumCustomWebUI(labResponse.User, Prompt.ForceLogin, true, directToAdfs))
                     .WithPrompt(Prompt.ForceLogin)
                     .WithLoginHint(labResponse.User.Upn)
                     .ExecuteAsync(new CancellationTokenSource(_interactiveAuthTimeout).Token)
                     .ConfigureAwait(false);

            userCacheAccess.AssertAccessCounts(2, 3);
            AssertCcsRoutingInformationIsSent(factory, labResponse);

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

            userCacheAccess.AssertAccessCounts(3, 3);
            Assert.IsFalse(userCacheAccess.LastAfterAccessNotificationArgs.IsApplicationCache);

            if (factory?.RequestsAndResponses != null)
            {
                factory.RequestsAndResponses.Clear();
            }

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

            Trace.WriteLine("Part 5 - Acquire a token silently with force refresh");
            result = await pca
                     .AcquireTokenSilent(s_scopes, account)
                     .WithForceRefresh(true)
                     .ExecuteAsync(CancellationToken.None)
                     .ConfigureAwait(false);

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

            Assert.IsFalse(userCacheAccess.LastAfterAccessNotificationArgs.IsApplicationCache);
            AssertCcsRoutingInformationIsSent(factory, labResponse);

            return(result);
        }
Ejemplo n.º 28
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");
        }
        public async Task FociSingInSignOutAsync()
        {
            LabResponse labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false);

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

            try
            {
                cacheFilePath = Path.GetTempFileName();

                CreateFamilyApps(labResponse, cacheFilePath, out IPublicClientApplication pca_fam1, out IPublicClientApplication pca_fam2, out IPublicClientApplication pca_nonFam);

                var userCacheAccess1 = pca_fam1.UserTokenCache.RecordAccess();
                var userCacheAccess2 = pca_fam2.UserTokenCache.RecordAccess();
                var userCacheAccess3 = pca_nonFam.UserTokenCache.RecordAccess();

                Trace.WriteLine("Get a token interactively with an app from the family.");
                AuthenticationResult authResult = await pca_fam1.AcquireTokenWithDeviceCode(s_scopes, deviceCodeResult =>
                {
                    SeleniumExtensions.PerformDeviceCodeLogin(
                        deviceCodeResult,
                        labResponse.User,
                        TestContext,
                        false);

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

                MsalAssert.AssertAuthResult(authResult, user);
                userCacheAccess1.AssertAccessCounts(0, 1);
                userCacheAccess2.AssertAccessCounts(0, 0);
                userCacheAccess3.AssertAccessCounts(0, 0);

                Trace.WriteLine("Get a token silently with another app from the family.");
                authResult = await pca_fam2.AcquireTokenSilent(s_scopes, user.Upn)
                             .ExecuteAsync()
                             .ConfigureAwait(false);

                MsalAssert.AssertAuthResult(authResult, user);
                userCacheAccess1.AssertAccessCounts(0, 1);
                userCacheAccess2.AssertAccessCounts(1, 1); // a write occurs because appA does not have an AT, so it needs to refresh the FRT
                userCacheAccess3.AssertAccessCounts(0, 0);

                Trace.WriteLine("Apps that are not part of the family cannot get tokens this way.");
                await AssertException.TaskThrowsAsync <MsalUiRequiredException>(() => pca_nonFam
                                                                                .AcquireTokenSilent(s_scopes, user.Upn)
                                                                                .ExecuteAsync())
                .ConfigureAwait(false);

                userCacheAccess1.AssertAccessCounts(0, 1);
                userCacheAccess2.AssertAccessCounts(1, 1);
                userCacheAccess3.AssertAccessCounts(1, 0);

                Trace.WriteLine("Sing-out from one app - sign out of all apps in the family");
                System.Collections.Generic.IEnumerable <IAccount> accounts = await pca_fam1.GetAccountsAsync().ConfigureAwait(false);

                await pca_fam1.RemoveAsync(accounts.Single()).ConfigureAwait(false);

                System.Collections.Generic.IEnumerable <IAccount> acc2 = await pca_fam2.GetAccountsAsync().ConfigureAwait(false);

                Assert.IsFalse(acc2.Any());
            }
            finally
            {
                if (cacheFilePath != null && File.Exists(cacheFilePath))
                {
                    File.Delete(cacheFilePath);
                }
            }
        }
Ejemplo n.º 30
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);
        }