Exemplo n.º 1
0
            /// <inheritdoc />
            protected override async Task <CacheExecutorResults> InternalExecuteAsync(CommandLineOptions options)
            {
                var    v1App    = PreRegisteredApps.CommonCacheTestV1;
                string resource = PreRegisteredApps.MsGraph;

                string[] scopes = new[]
                {
                    resource + "/user.read"
                };

                CommonCacheTestUtils.EnsureCacheFileDirectoryExists();
                var tokenCache = FileBasedTokenCacheHelper.GetUserCache(
                    CommonCacheTestUtils.MsalV2CacheFilePath,
                    CommonCacheTestUtils.AdalV3CacheFilePath);

                var app = new PublicClientApplication(v1App.ClientId, v1App.Authority, tokenCache);
                IEnumerable <IAccount> accounts = await app.GetAccountsAsync().ConfigureAwait(false);

                try
                {
                    var result = await app.AcquireTokenSilentAsync(scopes, accounts.FirstOrDefault(), app.Authority, false).ConfigureAwait(false);

                    Console.WriteLine($"got token for '{result.Account.Username}' from the cache");
                    return(new CacheExecutorResults(result.Account.Username, true));
                }
                catch (MsalUiRequiredException)
                {
                    var result = await app.AcquireTokenByUsernamePasswordAsync(scopes, options.Username, options.UserPassword.ToSecureString()).ConfigureAwait(false);

                    Console.WriteLine($"got token for '{result.Account.Username}' without the cache");
                    return(new CacheExecutorResults(result.Account.Username, false));
                }
            }
            /// <inheritdoc />
            protected override async Task<CacheExecutorResults> InternalExecuteAsync(CommandLineOptions options)
            {
                var app = PreRegisteredApps.CommonCacheTestV1;
                string resource = PreRegisteredApps.MsGraph;

                CommonCacheTestUtils.EnsureCacheFileDirectoryExists();
                var tokenCache = new FileBasedAdalV3TokenCache(CommonCacheTestUtils.AdalV3CacheFilePath);
                var authenticationContext = new AuthenticationContext(app.Authority, tokenCache);

                try
                {
                    var result = await authenticationContext.AcquireTokenSilentAsync(
                        resource,
                        app.ClientId,
                        new UserIdentifier(options.Username, UserIdentifierType.RequiredDisplayableId)).ConfigureAwait(false);

                    Console.WriteLine($"got token for '{result.UserInfo.DisplayableId}' from the cache");
                    return new CacheExecutorResults(result.UserInfo.DisplayableId, true);
                }
                catch (AdalSilentTokenAcquisitionException)
                {
                    var result = await authenticationContext.AcquireTokenAsync(
                        resource,
                        app.ClientId,
                        new UserPasswordCredential(options.Username, options.UserPassword)).ConfigureAwait(false);

                    Console.WriteLine($"got token for '{result.UserInfo.DisplayableId}' without the cache");
                    return new CacheExecutorResults(result.UserInfo.DisplayableId, false);
                }
            }
            /// <inheritdoc />
            protected override async Task <CacheExecutorResults> InternalExecuteAsync(CommandLineOptions options)
            {
                var    v1App    = PreRegisteredApps.CommonCacheTestV1;
                string resource = PreRegisteredApps.MsGraph;

                string[] scopes = new[]
                {
                    resource + "/user.read"
                };

                CommonCacheTestUtils.EnsureCacheFileDirectoryExists();

                var app = PublicClientApplicationBuilder
                          .Create(v1App.ClientId)
                          .WithAuthority(new Uri(v1App.Authority), true)
                          .WithLogging((LogLevel level, string message, bool containsPii) =>
                {
                    Console.WriteLine("{0}: {1}", level, message);
                })
                          .Build();

                FileBasedTokenCacheHelper.ConfigureUserCache(
                    options.CacheStorageType,
                    app.UserTokenCache,
                    CommonCacheTestUtils.AdalV3CacheFilePath,
                    CommonCacheTestUtils.MsalV2CacheFilePath,
                    CommonCacheTestUtils.MsalV3CacheFilePath);

                IEnumerable <IAccount> accounts = await app.GetAccountsAsync().ConfigureAwait(false);

                try
                {
                    var result = await app
                                 .AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                                 .WithAuthority(app.Authority)
                                 .WithForceRefresh(false)
                                 .ExecuteAsync(CancellationToken.None)
                                 .ConfigureAwait(false);

                    Console.WriteLine($"got token for '{result.Account.Username}' from the cache");
                    return(new CacheExecutorResults(result.Account.Username, true));
                }
                catch (MsalUiRequiredException)
                {
                    var result = await app
                                 .AcquireTokenByUsernamePassword(scopes, options.Username, options.UserPassword.ToSecureString())
                                 .ExecuteAsync(CancellationToken.None)
                                 .ConfigureAwait(false);

                    Console.WriteLine($"got token for '{result.Account.Username}' without the cache");
                    return(new CacheExecutorResults(result.Account.Username, false));
                }
            }
        public async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            LogExecution();

            CommonCacheTestUtils.DeleteAllTestCaches();
            CommonCacheTestUtils.EnsureCacheFileDirectoryExists();

            var cacheProgramFirst  = CacheProgramFactory.CreateCacheProgram(_firstProgram, _cacheStorageType);
            var cacheProgramSecond = CacheProgramFactory.CreateCacheProgram(_secondProgram, _cacheStorageType);

            var firstResults = await cacheProgramFirst.ExecuteAsync(_labUsers, cancellationToken).ConfigureAwait(false);

            var secondResults = await cacheProgramSecond.ExecuteAsync(_labUsers, cancellationToken).ConfigureAwait(false);

            Console.WriteLine();
            Console.WriteLine("------------------------------------");
            Console.WriteLine($"FirstResults: {_firstProgram}");
            Console.WriteLine("stdout:");
            Console.WriteLine(firstResults.StdOut);
            Console.WriteLine();
            Console.WriteLine("stderr:");
            Console.WriteLine(firstResults.StdErr);
            Console.WriteLine("------------------------------------");
            Console.WriteLine($"SecondResults: {_secondProgram}");
            Console.WriteLine("stdout:");
            Console.WriteLine(secondResults.StdOut);
            Console.WriteLine("stderr:");
            Console.WriteLine(secondResults.StdErr);
            Console.WriteLine("------------------------------------");
            Console.WriteLine();

            Assert.IsFalse(firstResults.ProcessExecutionFailed, $"{cacheProgramFirst.ExecutablePath} should not fail");
            Assert.IsFalse(secondResults.ProcessExecutionFailed, $"{cacheProgramSecond.ExecutablePath} should not fail");

            foreach (var upnResult in firstResults.ExecutionResults.Results)
            {
                Assert.IsFalse(upnResult.IsAuthResultFromCache, $"{upnResult.LabUserUpn} --> First result should not be from the cache");
                Assert.AreEqual(upnResult?.LabUserUpn?.ToLowerInvariant(), upnResult?.AuthResultUpn?.ToLowerInvariant());
            }

            foreach (var upnResult in secondResults.ExecutionResults.Results)
            {
                Assert.IsTrue(upnResult.IsAuthResultFromCache, $"{upnResult.LabUserUpn} --> Second result should be from the cache");
                Assert.AreEqual(upnResult?.LabUserUpn?.ToLowerInvariant(), upnResult?.AuthResultUpn?.ToLowerInvariant());
            }

            Assert.IsFalse(
                secondResults.ExecutionResults.IsError,
                "Second result should NOT have thrown an exception");

            PrintCacheInfo();
        }
Exemplo n.º 5
0
            /// <inheritdoc />
            protected override async Task <CacheExecutorResults> InternalExecuteAsync(CommandLineOptions options)
            {
                var    app      = PreRegisteredApps.CommonCacheTestV1;
                string resource = PreRegisteredApps.MsGraph;

                LoggerCallbackHandler.LogCallback = (LogLevel level, string message, bool containsPii) =>
                {
                    Console.WriteLine("{0}: {1}", level, message);
                };

                CommonCacheTestUtils.EnsureCacheFileDirectoryExists();
                var tokenCache = new FileBasedTokenCache(
                    options.CacheStorageType,
                    CommonCacheTestUtils.AdalV3CacheFilePath,
                    CommonCacheTestUtils.MsalV2CacheFilePath,
                    CommonCacheTestUtils.MsalV3CacheFilePath);

                var authenticationContext = new AuthenticationContext(app.Authority, tokenCache);

                var items = authenticationContext.TokenCache.ReadItems().ToList();

                Console.WriteLine("here come the cache items!: {0}", tokenCache.Count);
                foreach (var item in items)
                {
                    Console.WriteLine("here's a cache item!");
                    Console.WriteLine(item.DisplayableId);
                }

                Console.WriteLine("Calling ATS with username: {0}", options.Username);

                try
                {
                    var result = await authenticationContext.AcquireTokenSilentAsync(
                        resource,
                        app.ClientId,
                        new UserIdentifier(options.Username, UserIdentifierType.RequiredDisplayableId)).ConfigureAwait(false);

                    Console.WriteLine($"got token for '{result.UserInfo.DisplayableId}' from the cache");
                    return(new CacheExecutorResults(result.UserInfo.DisplayableId, true));
                }
                catch (AdalSilentTokenAcquisitionException)
                {
                    var result = await authenticationContext.AcquireTokenAsync(
                        resource,
                        app.ClientId,
                        new UserPasswordCredential(options.Username, options.UserPassword)).ConfigureAwait(false);

                    Console.WriteLine($"got token for '{result.UserInfo.DisplayableId}' without the cache");
                    return(new CacheExecutorResults(result.UserInfo.DisplayableId, false));
                }
            }
        public async Task ExecuteAsync(
            CacheProgramType firstProgram,
            CacheProgramType secondProgram,
            CancellationToken cancellationToken)
        {
            Console.WriteLine($"Running {firstProgram} -> {secondProgram}...");

            CommonCacheTestUtils.DeleteAllTestCaches();
            CommonCacheTestUtils.EnsureCacheFileDirectoryExists();

            await ExecuteCacheProgramAsync(firstProgram, true, cancellationToken).ConfigureAwait(false);
            await ExecuteCacheProgramAsync(secondProgram, false, cancellationToken).ConfigureAwait(false);

            PrintCacheInfo();
        }
            protected override async Task <CacheExecutorResults> InternalExecuteAsync(CommandLineOptions options)
            {
                var    v1App    = PreRegisteredApps.CommonCacheTestV1;
                string resource = PreRegisteredApps.MsGraph;
                string scope    = resource + "/user.read";

                CommonCacheTestUtils.EnsureCacheFileDirectoryExists();

                string scriptFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "TestMsalPython.py");

                return(await LanguageRunner.ExecuteAsync(
                           new PythonLanguageExecutor(scriptFilePath),
                           v1App.ClientId,
                           v1App.Authority,
                           scope,
                           options.Username,
                           options.UserPassword,
                           CommonCacheTestUtils.MsalV3CacheFilePath,
                           CancellationToken.None).ConfigureAwait(false));
            }
Exemplo n.º 8
0
            protected override async Task <CacheExecutorResults> InternalExecuteAsync(CommandLineOptions options)
            {
                var    v1App    = PreRegisteredApps.CommonCacheTestV1;
                string resource = PreRegisteredApps.MsGraph;
                string scope    = resource + "/user.read";

                CommonCacheTestUtils.EnsureCacheFileDirectoryExists();

                // TODO: figure out how we setup the public main program, compile it from .java to .class, and execute it
                // May need to have the JavaLanguageExecutor take a .java file and then have a separate compile
                // step on that class to build the java code and run it.
                string javaClassFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "SomeJavaClass.class");

                return(await LanguageRunner.ExecuteAsync(
                           new JavaLanguageExecutor(javaClassFilePath),
                           v1App.ClientId,
                           v1App.Authority,
                           scope,
                           options.Username,
                           options.UserPassword,
                           CommonCacheTestUtils.MsalV3CacheFilePath,
                           CancellationToken.None).ConfigureAwait(false));
            }
Exemplo n.º 9
0
        public async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            LogExecution();

            CommonCacheTestUtils.DeleteAllTestCaches();
            CommonCacheTestUtils.EnsureCacheFileDirectoryExists();

            var api     = new LabServiceApi();
            var labUser = api.GetLabResponse(
                new UserQuery
            {
                UserType        = UserType.Member,
                IsFederatedUser = false
            }).User;

            Console.WriteLine($"Received LabUser: {labUser.Upn} from LabServiceApi.");

            var cacheProgramFirst  = CacheProgramFactory.CreateCacheProgram(_firstProgram, _cacheStorageType);
            var cacheProgramSecond = CacheProgramFactory.CreateCacheProgram(_secondProgram, _cacheStorageType);

            var firstResults = await cacheProgramFirst.ExecuteAsync(labUser.Upn, labUser.GetOrFetchPassword(), cancellationToken).ConfigureAwait(false);

            var secondResults = await cacheProgramSecond.ExecuteAsync(labUser.Upn, labUser.GetOrFetchPassword(), cancellationToken).ConfigureAwait(false);

            Console.WriteLine();
            Console.WriteLine("------------------------------------");
            Console.WriteLine($"FirstResults: {_firstProgram}");
            Console.WriteLine("stdout:");
            Console.WriteLine(firstResults.StdOut);
            Console.WriteLine();
            Console.WriteLine("stderr:");
            Console.WriteLine(firstResults.StdErr);
            Console.WriteLine("------------------------------------");
            Console.WriteLine($"SecondResults: {_secondProgram}");
            Console.WriteLine("stdout:");
            Console.WriteLine(secondResults.StdOut);
            Console.WriteLine("stderr:");
            Console.WriteLine(secondResults.StdErr);
            Console.WriteLine("------------------------------------");
            Console.WriteLine();

            Assert.IsFalse(firstResults.ProcessExecutionFailed, $"{cacheProgramFirst.ExecutablePath} should not fail");
            Assert.IsFalse(secondResults.ProcessExecutionFailed, $"{cacheProgramSecond.ExecutablePath} should not fail");

            Assert.IsFalse(firstResults.ExecutionResults.ReceivedTokenFromCache, "First result should not be from the cache");

            if (File.Exists(CommonCacheTestUtils.AdalV3CacheFilePath))
            {
                Console.WriteLine($"Adal Cache Exists at: {CommonCacheTestUtils.AdalV3CacheFilePath}");
                Console.WriteLine("Adal Cache Size: " + Convert.ToInt32(new FileInfo(CommonCacheTestUtils.AdalV3CacheFilePath).Length));
            }
            else
            {
                Console.WriteLine($"Adal Cache DOES NOT EXIST at: {CommonCacheTestUtils.AdalV3CacheFilePath}");
            }

            if (File.Exists(CommonCacheTestUtils.MsalV2CacheFilePath))
            {
                Console.WriteLine($"MSAL V2 Cache Exists at: {CommonCacheTestUtils.MsalV2CacheFilePath}");
                Console.WriteLine("MSAL V2 Cache Size: " + Convert.ToInt32(new FileInfo(CommonCacheTestUtils.MsalV2CacheFilePath).Length));
            }
            else
            {
                Console.WriteLine($"MSAL V2 Cache DOES NOT EXIST at: {CommonCacheTestUtils.MsalV2CacheFilePath}");
            }

            if (File.Exists(CommonCacheTestUtils.MsalV3CacheFilePath))
            {
                Console.WriteLine($"MSAL V3 Cache Exists at: {CommonCacheTestUtils.MsalV3CacheFilePath}");
                Console.WriteLine("MSAL V3 Cache Size: " + Convert.ToInt32(new FileInfo(CommonCacheTestUtils.MsalV3CacheFilePath).Length));
            }
            else
            {
                Console.WriteLine($"MSAL V3 Cache DOES NOT EXIST at: {CommonCacheTestUtils.MsalV3CacheFilePath}");
            }

            if (_expectSecondTokenFromCache)
            {
                Assert.IsTrue(
                    secondResults.ExecutionResults.ReceivedTokenFromCache,
                    "Second result should be from the cache");
            }
            else
            {
                Assert.IsFalse(
                    secondResults.ExecutionResults.ReceivedTokenFromCache,
                    "Second result should NOT be from the cache");
            }

            if (_expectSecondTokenException)
            {
                Assert.IsTrue(
                    secondResults.ExecutionResults.IsError,
                    "Second result should have thrown an exception");
            }
            else
            {
                Assert.IsFalse(
                    secondResults.ExecutionResults.IsError,
                    "Second result should NOT have thrown an exception");
            }
        }
Exemplo n.º 10
0
        public async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            LogExecution();

            CommonCacheTestUtils.DeleteAllTestCaches();
            CommonCacheTestUtils.EnsureCacheFileDirectoryExists();

            var api     = new LabServiceApi(new KeyVaultSecretsProvider());
            var labUser = api.GetLabResponse(
                new UserQuery
            {
                UserType        = UserType.Member,
                IsFederatedUser = false
            }).User;

            Console.WriteLine($"Received LabUser: {labUser.Upn} from LabServiceApi.");

            var cacheProgramFirst  = CacheProgramFactory.CreateCacheProgram(_firstProgram);
            var cacheProgramSecond = CacheProgramFactory.CreateCacheProgram(_secondProgram);

            var firstResults = await cacheProgramFirst.ExecuteAsync(labUser.Upn, labUser.Password, cancellationToken).ConfigureAwait(false);

            var secondResults = await cacheProgramSecond.ExecuteAsync(labUser.Upn, labUser.Password, cancellationToken).ConfigureAwait(false);

            Console.WriteLine($"FirstResults: {_firstProgram}");
            Console.WriteLine($"stdout: {firstResults.StdOut}");
            Console.WriteLine($"stderr: {firstResults.StdErr}");

            Console.WriteLine($"SecondResults: {_secondProgram}");
            Console.WriteLine($"stdout: {secondResults.StdOut}");
            Console.WriteLine($"stderr: {secondResults.StdErr}");

            Assert.IsFalse(firstResults.ProcessExecutionFailed, $"{cacheProgramFirst.ExecutablePath} should not fail");
            Assert.IsFalse(secondResults.ProcessExecutionFailed, $"{cacheProgramSecond.ExecutablePath} should not fail");

            Assert.IsFalse(firstResults.ExecutionResults.ReceivedTokenFromCache, "First result should not be from the cache");

            if (File.Exists(CommonCacheTestUtils.AdalV3CacheFilePath))
            {
                Console.WriteLine($"Adal Cache Exists at: {CommonCacheTestUtils.AdalV3CacheFilePath}");
                Console.WriteLine("Adal Cache Size: " + Convert.ToInt32(new FileInfo(CommonCacheTestUtils.AdalV3CacheFilePath).Length));
            }
            else
            {
                Console.WriteLine($"Adal Cache DOES NOT EXIST at: {CommonCacheTestUtils.AdalV3CacheFilePath}");
            }

            if (File.Exists(CommonCacheTestUtils.MsalV2CacheFilePath))
            {
                Console.WriteLine($"MSAL Cache Exists at: {CommonCacheTestUtils.MsalV2CacheFilePath}");
                Console.WriteLine("MSAL Cache Size: " + Convert.ToInt32(new FileInfo(CommonCacheTestUtils.MsalV2CacheFilePath).Length));
            }
            else
            {
                Console.WriteLine($"MSAL Cache DOES NOT EXIST at: {CommonCacheTestUtils.MsalV2CacheFilePath}");
            }

            // TODO: cache size seems to be variant/inconsistent.  Need to validate if it should be the same every time.
            //if (_expectedAdalCacheSizeBytes > 0)
            //{
            //    Assert.AreEqual(_expectedAdalCacheSizeBytes, Convert.ToInt32(new FileInfo(CommonCacheTestUtils.AdalV3CacheFilePath).Length), "Expected Adal Cache Size");
            //}
            //if (_expectedMsalCacheSizeBytes > 0)
            //{
            //    Assert.AreEqual(_expectedMsalCacheSizeBytes, Convert.ToInt32(new FileInfo(CommonCacheTestUtils.MsalV2CacheFilePath).Length), "Expected Msal Cache Size");
            //}

            if (_expectSecondTokenFromCache)
            {
                Assert.IsTrue(
                    secondResults.ExecutionResults.ReceivedTokenFromCache,
                    "Second result should be from the cache");
            }
            else
            {
                Assert.IsFalse(
                    secondResults.ExecutionResults.ReceivedTokenFromCache,
                    "Second result should NOT be from the cache");
            }

            if (_expectSecondTokenException)
            {
                Assert.IsTrue(
                    secondResults.ExecutionResults.IsError,
                    "Second result should have thrown an exception");
            }
            else
            {
                Assert.IsFalse(
                    secondResults.ExecutionResults.IsError,
                    "Second result should NOT have thrown an exception");
            }
        }