Example #1
0
        private static async Task RunConsoleAppLogicAsync(IPublicClientApplication pca)
        {
            while (true)
            {
                Console.Clear();

                Console.WriteLine("Authority: " + GetAuthority());
                await DisplayAccountsAsync(pca).ConfigureAwait(false);

                // display menu
                Console.WriteLine(@"
                        1. IWA
                        2. Acquire Token with Username and Password
                        3. Acquire Token with Device Code
                        5. Acquire Token Interactive 
                        6. Acquire Token Silently
                        7. Acquire Interactive (logic in netstandard, default authority)
                        8. Clear cache
                        9. Rotate Tenant ID
                        0. Exit App
                    Enter your Selection: ");
                int.TryParse(Console.ReadLine(), out var selection);

                Task <AuthenticationResult> authTask = null;

                try
                {
                    switch (selection)
                    {
                    case 1: // acquire token
                        authTask = pca.AcquireTokenByIntegratedWindowsAuth(s_scopes).WithUsername(s_username).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case 2: // acquire token u/p
                        SecureString password = GetPasswordFromConsole();
                        authTask = pca.AcquireTokenByUsernamePassword(s_scopes, s_username, password).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case 3:
                        authTask = pca.AcquireTokenWithDeviceCode(
                            s_scopes,
                            deviceCodeResult =>
                        {
                            Console.WriteLine(deviceCodeResult.Message);
                            return(Task.FromResult(0));
                        }).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case 5: // acquire token interactive

                        CancellationTokenSource cts = new CancellationTokenSource();
                        authTask = pca.AcquireTokenInteractive(s_scopes)
                                   .WithUseEmbeddedWebView(false)
                                   .WithSystemWebViewOptions(new SystemWebViewOptions()
                        {
                            //BrowserRedirectSuccess = new Uri("https://www.google.com"),
                            HtmlMessageSuccess = "All good, close the browser!",

                            OpenBrowserAsync = (Uri u) =>
                            {
                                string url = u.AbsoluteUri;
                                url        = url.Replace("&", "^&");
                                Process.Start(new ProcessStartInfo("cmd", $"/c start msedge {url}")
                                {
                                    CreateNoWindow = true
                                });
                                return(Task.FromResult(0));
                            }
                        })
                                   .ExecuteAsync(cts.Token);

                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case 6: // acquire token silent
                        IAccount account = pca.GetAccountsAsync().Result.FirstOrDefault();
                        if (account == null)
                        {
                            Log(LogLevel.Error, "Test App Message - no accounts found, AcquireTokenSilentAsync will fail... ", false);
                        }

                        authTask = pca.AcquireTokenSilent(s_scopes, account).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case 7:
                        CancellationTokenSource cts2 = new CancellationTokenSource();
                        var authenticator            = new NetStandardAuthenticator(Log, CacheFilePath);
                        await FetchTokenAndCallGraphAsync(pca, authenticator.GetTokenInteractiveAsync(cts2.Token)).ConfigureAwait(false);

                        break;

                    case 8:
                        var accounts = await pca.GetAccountsAsync().ConfigureAwait(false);

                        foreach (var acc in accounts)
                        {
                            await pca.RemoveAsync(acc).ConfigureAwait(false);
                        }

                        break;

                    case 9:

                        s_currentTid = (s_currentTid + 1) % s_tids.Length;
                        pca          = CreatePca();
                        RunConsoleAppLogicAsync(pca).Wait();
                        break;


                    case 0:
                        return;

                    default:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Log(LogLevel.Error, ex.Message, false);
                    Log(LogLevel.Error, ex.StackTrace, false);
                }

                Console.WriteLine("\n\nHit 'ENTER' to continue...");
                Console.ReadLine();
            }
        }
Example #2
0
        private static async Task RunConsoleAppLogicAsync(
            IPublicClientApplication pca,
            IConfidentialClientApplication cca)
        {
            while (true)
            {
                Console.Clear();

                Console.WriteLine("Authority: " + GetAuthority());
                await DisplayAccountsAsync(pca).ConfigureAwait(false);

                // display menu
                Console.WriteLine(@"
                        1. IWA
                        2. Acquire Token with Username and Password
                        3. Acquire Token with Device Code
                        4. Acquire Token Interactive 
                        5. Acquire Token Interactive via NetStandard lib
                        6. Acquire Token Silently
                        7. Acquire Token Silently - multiple requests in parallel
                        8. Acquire SSH Cert Interactive
                        9. Client Credentials 
                        c. Clear cache
                        r. Rotate Tenant ID
                        e. Expire all ATs
                        x. Exit app
                    Enter your Selection: ");
                char.TryParse(Console.ReadLine(), out var selection);

                Task <AuthenticationResult> authTask = null;

                try
                {
                    switch (selection)
                    {
                    case '1':     // acquire token
                        authTask = pca.AcquireTokenByIntegratedWindowsAuth(s_scopes).WithUsername(s_username).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case '2':     // acquire token u/p
                        SecureString password = GetPasswordFromConsole();
                        authTask = pca.AcquireTokenByUsernamePassword(s_scopes, s_username, password).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case '3':
                        authTask = pca.AcquireTokenWithDeviceCode(
                            s_scopes,
                            deviceCodeResult =>
                        {
                            Console.WriteLine(deviceCodeResult.Message);
                            return(Task.FromResult(0));
                        }).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case '4':

                        authTask = pca.AcquireTokenInteractive(s_scopes)
                                   .WithPrompt(Prompt.Consent)
                                   .ExecuteAsync(CancellationToken.None);

                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case '6':     // acquire token silent
                        IAccount account = pca.GetAccountsAsync().Result.FirstOrDefault();
                        if (account == null)
                        {
                            Log(LogLevel.Error, "Test App Message - no accounts found, AcquireTokenSilentAsync will fail... ", false);
                        }

                        authTask = pca.AcquireTokenSilent(s_scopes, account).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case '7':     // acquire token silent - one request per IAccount
                        var accounts = await pca.GetAccountsAsync().ConfigureAwait(false);

                        Task <AuthenticationResult>[] tasks = accounts
                                                              .Select(acc => pca.AcquireTokenSilent(s_scopes, acc).ExecuteAsync())
                                                              .ToArray();

                        AuthenticationResult[] result = await Task.WhenAll(tasks).ConfigureAwait(false);

                        foreach (var ar in result)
                        {
                            Console.BackgroundColor = ConsoleColor.DarkGreen;
                            Console.WriteLine($"Got a token for {ar.Account.Username} ");
                            Console.ResetColor();
                        }

                        break;

                    case '5':     // Acquire Token Interactive via NetStandard lib
                        CancellationTokenSource cts2 = new CancellationTokenSource();
                        var authenticator            = new NetStandardAuthenticator(Log, UserCacheFile);
                        await FetchTokenAndCallGraphAsync(pca, authenticator.GetTokenInteractiveAsync(cts2.Token)).ConfigureAwait(false);

                        break;

                    case '8':     // acquire SSH cert
                        RSACryptoServiceProvider rsa        = new RSACryptoServiceProvider();
                        RSAParameters            rsaKeyInfo = rsa.ExportParameters(false);

                        string modulus = Base64UrlHelpers.Encode(rsaKeyInfo.Modulus);
                        string exp     = Base64UrlHelpers.Encode(rsaKeyInfo.Exponent);
                        string jwk     = $"{{\"kty\":\"RSA\", \"n\":\"{modulus}\", \"e\":\"{exp}\"}}";

                        CancellationTokenSource cts = new CancellationTokenSource();
                        authTask = pca.AcquireTokenInteractive(s_scopes)
                                   .WithUseEmbeddedWebView(false)
                                   .WithExtraQueryParameters(new Dictionary <string, string>()
                        {
                            { "dc", "prod-wst-test1" },
                            { "slice", "test" },
                            { "sshcrt", "true" }
                        })
                                   .WithSSHCertificateAuthenticationScheme(jwk, "1")
                                   .WithSystemWebViewOptions(new SystemWebViewOptions()
                        {
                            HtmlMessageSuccess = "All good, close the browser!",
                            OpenBrowserAsync   = SystemWebViewOptions.OpenWithEdgeBrowserAsync
                        })
                                   .ExecuteAsync(cts.Token);

                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case '9':

                        authTask = cca.AcquireTokenForClient(
                            new[] { "https://graph.microsoft.com/.default" }).
                                   ExecuteAsync();

                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case 'c':
                        var accounts2 = await pca.GetAccountsAsync().ConfigureAwait(false);

                        foreach (var acc in accounts2)
                        {
                            await pca.RemoveAsync(acc).ConfigureAwait(false);
                        }

                        break;

                    case 'r':     // rotate tid

                        s_currentTid = (s_currentTid + 1) % s_tids.Length;
                        pca          = CreatePca();
                        cca          = CreateCca();
                        RunConsoleAppLogicAsync(pca, cca).Wait();
                        break;

                    case 'e':     // expire all ATs

                        var tokenCacheInternal = pca.UserTokenCache as ITokenCacheInternal;
                        var ats = tokenCacheInternal.Accessor.GetAllAccessTokens();
                        // set access tokens as expired
                        foreach (var accessItem in ats)
                        {
                            accessItem.ExpiresOnUnixTimestamp =
                                ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds)
                                .ToString(CultureInfo.InvariantCulture);

                            tokenCacheInternal.Accessor.SaveAccessToken(accessItem);
                        }

                        TokenCacheNotificationArgs args = new TokenCacheNotificationArgs(
                            pca.UserTokenCache as ITokenCacheInternal, s_clientIdForPublicApp, null, true);

                        await tokenCacheInternal.OnAfterAccessAsync(args).ConfigureAwait(false);

                        break;

                    case 'x':
                        return;

                    default:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Log(LogLevel.Error, ex.Message, false);
                    Log(LogLevel.Error, ex.StackTrace, false);
                }

                Console.WriteLine("\n\nHit 'ENTER' to continue...");
                Console.ReadLine();
            }
        }
        private static async Task RunConsoleAppLogicAsync(IPublicClientApplication pca)
        {
            while (true)
            {
                Console.Clear();

                Console.WriteLine("Authority: " + GetAuthority());
                await DisplayAccountsAsync(pca).ConfigureAwait(false);

                // display menu
                Console.WriteLine(@"
                        1. IWA
                        2. Acquire Token with Username and Password
                        3. Acquire Token with Device Code
                        4. Acquire Token Interactive (via CustomWebUI)
                        5. Acquire Token Interactive
                        6. Acquire Token Silently
                        7. Acquire Interactive (logic in netstandard, default authority)
                        8. Clear cache
                        9. Rotate Tenant ID
                        0. Exit App
                    Enter your Selection: ");
                int.TryParse(Console.ReadLine(), out var selection);

                Task <AuthenticationResult> authTask = null;

                try
                {
                    switch (selection)
                    {
                    case 1:     // acquire token
                        authTask = pca.AcquireTokenByIntegratedWindowsAuth(s_scopes).WithUsername(s_username).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case 2:     // acquire token u/p
                        SecureString password = GetPasswordFromConsole();
                        authTask = pca.AcquireTokenByUsernamePassword(s_scopes, s_username, password).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case 3:
                        authTask = pca.AcquireTokenWithDeviceCode(
                            s_scopes,
                            deviceCodeResult =>
                        {
                            Console.WriteLine(deviceCodeResult.Message);
                            return(Task.FromResult(0));
                        }).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case 4:     // acquire token interactive with custom web ui

                        authTask = pca.AcquireTokenInteractive(s_scopes)
                                   .WithCustomWebUi(new DefaultOsBrowserWebUi()) // make sure you've configured a redirect uri of "http://localhost" or "http://localhost:1234" in the _pca builder
                                   .ExecuteAsync(CancellationToken.None);

                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case 5:     // acquire token interactive

                        var options = new SystemWebViewOptions()
                        {
                            //BrowserRedirectSuccess = new Uri("https://www.bing.com?q=why+is+42+the+meaning+of+life")
                            OpenBrowserAsync = SystemWebViewOptions.OpenWithEdgeBrowserAsync
                        };

                        var cts = new CancellationTokenSource();
                        authTask = pca.AcquireTokenInteractive(s_scopes)
                                   .WithSystemWebViewOptions(options)
                                   .ExecuteAsync(cts.Token);

                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case 6:     // acquire token silent
                        IAccount account = pca.GetAccountsAsync().Result.FirstOrDefault();
                        if (account == null)
                        {
                            Log(LogLevel.Error, "Test App Message - no accounts found, AcquireTokenSilentAsync will fail... ", false);
                        }

                        authTask = pca.AcquireTokenSilent(s_scopes, account).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case 7:
                        CancellationTokenSource  cts2          = new CancellationTokenSource();
                        NetStandardAuthenticator authenticator = new NetStandardAuthenticator(Log, CacheFilePath);
                        await FetchTokenAndCallGraphAsync(pca, authenticator.GetTokenInteractiveAsync(cts2.Token)).ConfigureAwait(false);

                        break;

                    case 8:
                        var accounts = await pca.GetAccountsAsync().ConfigureAwait(false);

                        foreach (var acc in accounts)
                        {
                            await pca.RemoveAsync(acc).ConfigureAwait(false);
                        }

                        break;

                    case 9:

                        s_currentTid = (s_currentTid + 1) % s_tids.Length;
                        pca          = CreatePca();
                        RunConsoleAppLogicAsync(pca).Wait();
                        break;

                    case 0:
                        return;

                    default:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Log(LogLevel.Error, ex.Message, false);
                    Log(LogLevel.Error, ex.StackTrace, false);
                }

                Console.WriteLine("\n\nHit 'ENTER' to continue...");
                Console.ReadLine();
            }
        }
        private static async Task RunConsoleAppLogicAsync(IPublicClientApplication pca)
        {
            while (true)
            {
                Console.Clear();

                Console.WriteLine("Authority: " + GetAuthority());
                await DisplayAccountsAsync(pca).ConfigureAwait(false);

                // display menu
                Console.WriteLine(@"
                        1. IWA
                        2. Acquire Token with Username and Password
                        3. Acquire Token with Device Code
                        4. Acquire Token Interactive 
                        5. Acquire Token Interactive via NetStandard lib
                        6. Acquire Token Silently
                        7. Acquire Token Silently - multiple requests in parallel
                        8. Clear cache
                        9. Rotate Tenant ID
                        0. Expire all ATs
                        x. Exit app
                    Enter your Selection: ");
                char.TryParse(Console.ReadLine(), out var selection);

                Task <AuthenticationResult> authTask = null;

                try
                {
                    switch (selection)
                    {
                    case '1':     // acquire token
                        authTask = pca.AcquireTokenByIntegratedWindowsAuth(s_scopes).WithUsername(s_username).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case '2':     // acquire token u/p
                        SecureString password = GetPasswordFromConsole();
                        authTask = pca.AcquireTokenByUsernamePassword(s_scopes, s_username, password).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case '3':
                        authTask = pca.AcquireTokenWithDeviceCode(
                            s_scopes,
                            deviceCodeResult =>
                        {
                            Console.WriteLine(deviceCodeResult.Message);
                            return(Task.FromResult(0));
                        }).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case '4':     // acquire token interactive

                        CancellationTokenSource cts = new CancellationTokenSource();
                        authTask = pca.AcquireTokenInteractive(s_scopes)
                                   .WithUseEmbeddedWebView(false)
                                   .WithSystemWebViewOptions(new SystemWebViewOptions()
                        {
                            //BrowserRedirectSuccess = new Uri("https://www.google.com"),
                            HtmlMessageSuccess = "All good, close the browser!",

                            //OpenBrowserAsync = (Uri u) =>
                            //{
                            //    string url = u.AbsoluteUri;
                            //    url = url.Replace("&", "^&");
                            //    Process.Start(new ProcessStartInfo("cmd", $"/c start msedge {url}") { CreateNoWindow = true });
                            //    return Task.FromResult(0);
                            //}
                            OpenBrowserAsync = SystemWebViewOptions.OpenWithEdgeBrowserAsync
                        })
                                   .ExecuteAsync(cts.Token);

                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case '6':     // acquire token silent
                        IAccount account = pca.GetAccountsAsync().Result.FirstOrDefault();
                        if (account == null)
                        {
                            Log(LogLevel.Error, "Test App Message - no accounts found, AcquireTokenSilentAsync will fail... ", false);
                        }

                        authTask = pca.AcquireTokenSilent(s_scopes, account).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false);

                        break;

                    case '7':     // acquire token silent - one request per IAccount
                        var accounts = await pca.GetAccountsAsync().ConfigureAwait(false);

                        Task <AuthenticationResult>[] tasks = accounts
                                                              .Select(acc => pca.AcquireTokenSilent(s_scopes, acc).ExecuteAsync())
                                                              .ToArray();

                        AuthenticationResult[] result = await Task.WhenAll(tasks).ConfigureAwait(false);

                        foreach (var ar in result)
                        {
                            Console.BackgroundColor = ConsoleColor.DarkGreen;
                            Console.WriteLine($"Got a token for {ar.Account.Username} ");
                            Console.ResetColor();
                        }

                        break;

                    case '5':     // Acquire Token Interactive via NetStandard lib
                        CancellationTokenSource cts2 = new CancellationTokenSource();
                        var authenticator            = new NetStandardAuthenticator(Log, CacheFilePath);
                        await FetchTokenAndCallGraphAsync(pca, authenticator.GetTokenInteractiveAsync(cts2.Token)).ConfigureAwait(false);

                        break;

                    case '8':
                        var accounts2 = await pca.GetAccountsAsync().ConfigureAwait(false);

                        foreach (var acc in accounts2)
                        {
                            await pca.RemoveAsync(acc).ConfigureAwait(false);
                        }

                        break;

                    case '9':

                        s_currentTid = (s_currentTid + 1) % s_tids.Length;
                        pca          = CreatePca();
                        RunConsoleAppLogicAsync(pca).Wait();
                        break;

                    case '0':

                        var tokenCacheInternal = pca.UserTokenCache as ITokenCacheInternal;
                        var ats = tokenCacheInternal.Accessor.GetAllAccessTokens();
                        // set access tokens as expired
                        foreach (var accessItem in ats)
                        {
                            accessItem.ExpiresOnUnixTimestamp =
                                ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds)
                                .ToString(CultureInfo.InvariantCulture);

                            tokenCacheInternal.Accessor.SaveAccessToken(accessItem);
                        }

                        TokenCacheNotificationArgs args = new TokenCacheNotificationArgs(
                            pca.UserTokenCache as ITokenCacheInternal, s_clientIdForPublicApp, null, true);

                        await tokenCacheInternal.OnAfterAccessAsync(args).ConfigureAwait(false);

                        break;

                    case 'x':
                        return;

                    default:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Log(LogLevel.Error, ex.Message, false);
                    Log(LogLevel.Error, ex.StackTrace, false);
                }

                Console.WriteLine("\n\nHit 'ENTER' to continue...");
                Console.ReadLine();
            }
        }