Пример #1
0
        private static async Task RunConsoleAppLogicAsync(
            IPublicClientApplication pca)
        {
            while (true)
            {
                Console.Clear();

                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.WriteLine($"" +
                                  $"IsDesktopSession: {pca.IsUserInteractive()}, " +
                                  $"IsEmbeddedWebViewAvailable: {pca.IsEmbeddedWebViewAvailable()} " +
                                  $"IsEmbeddedWebViewAvailable: {pca.IsSystemWebViewAvailable()}");

                Console.WriteLine("Authority: " + GetAuthority());
                Console.WriteLine("Use WAM: " + s_useBroker);
                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                         
                        $. Acquire Token Interactive with login hint
                        5. Acquire Token Silently
                        6. Acquire Token Silently - multiple requests in parallel
                        7. Acquire SSH Cert Interactive
                        8. Client Credentials 
                        9. Get Account with ID
                        a. Acquire Token Silently with MSA passthrough workaround
                        p. Toggle POP (currently {(s_usePoP ? " ON " : " OFF ")}) 
        private static async Task RunConsoleAppLogicAsync(IPublicClientApplication pca)
        {
            while (true)
            {
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.WriteLine($"" +
                                  $"IsDesktopSession: {pca.IsUserInteractive()}, " +
                                  $"IsEmbeddedWebViewAvailable: {pca.IsEmbeddedWebViewAvailable()} " +
                                  $"IsEmbeddedWebViewAvailable: {pca.IsSystemWebViewAvailable()}");

                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. Confidential Client
                        8. Clear cache
                        9. Rotate Tenant ID
                       10. Acquire Token Interactive with Chrome
                        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:
                        for (int i = 0; i < 100; i++)
                        {
                            var cca = CreateCca();

                            var resultX = await cca.AcquireTokenForClient(
                                new[] { "https://graph.microsoft.com/.default" })
                                          //.WithForceRefresh(true)
                                          .ExecuteAsync()
                                          .ConfigureAwait(false);

                            await Task.Delay(500).ConfigureAwait(false);

                            Console.WriteLine("Got a token");
                        }

                        Console.WriteLine("Finished");
                        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 10:     // acquire token interactive with Chrome

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

                        var ctsChrome = new CancellationTokenSource();
                        authTask = pca.AcquireTokenInteractive(s_scopes)
                                   .WithSystemWebViewOptions(optionsChrome)
                                   .ExecuteAsync(ctsChrome.Token);

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

                        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 async void SignIn(object sender = null, RoutedEventArgs args = null)
        {
            var accounts = (await _app.GetAccountsAsync()).ToList();

            // If there is already a token in the cache, clear the cache and update the label on the button.
            if (SignInButton.Content.ToString() == ClearCacheString)
            {
                TodoList.ItemsSource = string.Empty;

                // Clears the library cache. Does not affect the browser cookies.
                while (accounts.Any())
                {
                    await _app.RemoveAsync(accounts.First());

                    accounts = (await _app.GetAccountsAsync()).ToList();
                }

                SignInButton.Content = SignInString;
                UserName.Content     = Properties.Resources.UserNotSignedIn;
                return;
            }

            // Get an access token to call the To Do list service.
            try
            {
                var result = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
                             .ExecuteAsync()
                             .ConfigureAwait(false);

                Dispatcher.Invoke(() =>
                {
                    SignInButton.Content = ClearCacheString;
                    SetUserName(result.Account);
                    GetTodoList();
                }
                                  );
            }
            catch (MsalUiRequiredException)
            {
                try
                {
                    // Force a sign-in (Prompt.SelectAccount), as the MSAL web browser might contain cookies for the current user
                    // and we don't necessarily want to re-sign-in the same user
                    var builder = _app.AcquireTokenInteractive(Scopes)
                                  .WithAccount(accounts.FirstOrDefault())
                                  .WithPrompt(Prompt.SelectAccount);

                    if (!_app.IsEmbeddedWebViewAvailable())
                    {
                        // You app should install the embedded browser WebView2 https://aka.ms/msal-net-webview2
                        // but if for some reason this is not possible, you can fall back to the system browser
                        // in this case, the redirect uri needs to be set to "http://localhost"
                        builder = builder.WithUseEmbeddedWebView(false);
                    }

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

                    Dispatcher.Invoke(() =>
                    {
                        SignInButton.Content = ClearCacheString;
                        SetUserName(result.Account);
                        GetTodoList();
                    }
                                      );
                }
                catch (MsalException ex)
                {
                    if (ex.ErrorCode == "access_denied")
                    {
                        // The user canceled sign in, take no action.
                    }
                    else
                    {
                        // An unexpected error occurred.
                        string message = ex.Message;
                        if (ex.InnerException != null)
                        {
                            message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                        }

                        MessageBox.Show(message);
                    }

                    Dispatcher.Invoke(() =>
                    {
                        UserName.Content = Properties.Resources.UserNotSignedIn;
                    });
                }
            }
        }