Example #1
0
        public async Task DefaultOsBrowserWebUi_CustomBrowser_Async()
        {
            bool customOpenBrowserCalled = false;
            var  options = new SystemWebViewOptions()
            {
                OpenBrowserAsync = (Uri u) =>
                {
                    customOpenBrowserCalled = true;
                    return(Task.FromResult(0));
                }
            };

            var webUI          = CreateTestWebUI(options);
            var requestContext = new RequestContext(TestCommon.CreateDefaultServiceBundle(), Guid.NewGuid());
            var responseUri    = new Uri(TestAuthorizationResponseUri);

            _tcpInterceptor.ListenToSingleRequestAndRespondAsync(
                TestPort,
                "/",
                Arg.Any <Func <Uri, MessageAndHttpCode> >(),
                CancellationToken.None)
            .Returns(Task.FromResult(responseUri));

            // Act
            AuthorizationResult authorizationResult = await webUI.AcquireAuthorizationAsync(
                new Uri(TestAuthorizationRequestUri),
                new Uri(TestRedirectUri),
                requestContext,
                CancellationToken.None).ConfigureAwait(false);

            // Assert that we didn't open the browser using platform proxy
            await _platformProxy.DidNotReceiveWithAnyArgs().StartDefaultOsBrowserAsync(default, requestContext.ServiceBundle.Config.IsBrokerEnabled)
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultOsBrowserWebUi"/> class.
        /// </summary>
        /// <param name="logger">Logger.</param>
        public DefaultOsBrowserWebUi(
            ILogger logger)
        {
            this.webViewOptions = new SystemWebViewOptions();

            this.uriInterceptor = new HttpListenerInterceptor(logger);
        }
 private async Task AcquireTokenInteractiveWithChromeEdgeAsync(Prompt prompt)
 {
     try
     {
         await SystemWebViewOptions.OpenWithChromeEdgeBrowserAsync(new Uri("https://localhost")).ConfigureAwait(false);
     }
     catch (Exception exception)
     {
         CreateExceptionMessage(exception);
     }
 }
        public DefaultOsBrowserWebUi(
            IPlatformProxy proxy,
            ICoreLogger logger,
            SystemWebViewOptions webViewOptions,
            /* for test */ IUriInterceptor uriInterceptor = null)
        {
            _logger         = logger ?? throw new ArgumentNullException(nameof(logger));
            _webViewOptions = webViewOptions;
            _platformProxy  = proxy ?? throw new ArgumentNullException(nameof(proxy));

            _uriInterceptor = uriInterceptor ?? new HttpListenerInterceptor(_logger);
        }
        public async Task TestAcquireTokenInteractive_Options_Async()
        {
            var options = new SystemWebViewOptions();
            await AcquireTokenInteractiveParameterBuilder.Create(_harness.Executor, MsalTestConstants.Scope)
            .WithSystemWebViewOptions(options)
            .ExecuteAsync()
            .ConfigureAwait(false);

            _harness.ValidateCommonParameters(ApiEvent.ApiIds.AcquireTokenInteractive);
            _harness.ValidateInteractiveParameters(
                expectedEmbeddedWebView: WebViewPreference.System, // If system webview options are set, force usage of system webview
                browserOptions: options);
        }
        public async Task TestAcquireTokenInteractive_EmbeddedAndSystemOptions_Async()
        {
            var options = new SystemWebViewOptions();
            var ex      = await AssertException.TaskThrowsAsync <MsalClientException>(() =>

                                                                                      AcquireTokenInteractiveParameterBuilder.Create(_harness.Executor, MsalTestConstants.Scope)
                                                                                      .WithSystemWebViewOptions(options)
                                                                                      .WithUseEmbeddedWebView(true)
                                                                                      .ExecuteAsync()
                                                                                      ).ConfigureAwait(false);

            Assert.AreEqual(MsalError.SystemWebviewOptionsNotApplicable, ex.ErrorCode);
        }
Example #7
0
 public void ValidateInteractiveParameters(
     IAccount expectedAccount = null,
     IEnumerable <string> expectedExtraScopesToConsent = null,
     string expectedLoginHint            = null,
     string expectedPromptValue          = null,
     ICustomWebUi expectedCustomWebUi    = null,
     SystemWebViewOptions browserOptions = null)
 {
     ValidateInteractiveParameters(
         WebViewPreference.NotSpecified,
         expectedAccount,
         expectedExtraScopesToConsent,
         expectedLoginHint,
         expectedPromptValue,
         expectedCustomWebUi,
         browserOptions);
 }
Example #8
0
        private void ButtonSignIn_Click(object sender, RoutedEventArgs e)
        {
            AuthenticationResult authResult = null;

            var accounts = _publicClientApp.GetAccountsAsync().Result;

            try
            {
                var firstAccount = _publicClientApp.GetAccountsAsync().Result.FirstOrDefault();
                authResult = _publicClientApp.AcquireTokenSilent(_scopes, firstAccount).ExecuteAsync().Result;
            }
            catch (MsalUiRequiredException ex)
            {
                // A MsalUiRequiredException happened on AcquireTokenSilent.
                // This indicates you need to call AcquireTokenInteractive to acquire a token
                System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

                try
                {
                    // MSAL cannot detect if the user navigates away or simply closes the browser. Apps using this technique are encouraged to define a timeout (via CancellationToken).
                    // We recommend a timeout of at least a few minutes, to take into account cases where the user is prompted to change password or perform 2FA.
                    var cancellationToken = new CancellationTokenSource((int)TimeSpan.FromMinutes(3).TotalMilliseconds).Token;
                    var options           = new SystemWebViewOptions()
                    {
                        HtmlMessageError       = "<p> An error occured: {0}. Details {1}</p>",
                        BrowserRedirectSuccess = new Uri("https://www.microsoft.com"),
                    };

                    authResult = _publicClientApp.AcquireTokenInteractive(_scopes)
                                 .WithAccount(accounts.FirstOrDefault())
                                 .WithPrompt(Prompt.SelectAccount)
                                                                // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-uses-web-browser#net-core-does-not-support-embedded-browser
                                 .WithUseEmbeddedWebView(false) //this line is not required. The default is false, an exception is thrown if this is set to true because .NET Core does not provide an embedded UI.
                                 .WithSystemWebViewOptions(options)
                                 .ExecuteAsync(cancellationToken).Result;
                }
                catch (MsalException msalex)
                {
                    throw new InvalidOperationException($"Error Acquiring Token:{System.Environment.NewLine}{msalex}", msalex);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}");
            }
        }
        /// <summary>
        /// Sign in with your Microsoft Account<br/>
        /// When calling it, a new web browser tab will open in your default browser that will prompt you to log in with your Microsoft Account. After it, if everything went well, you'll be prompted to close the tab and the process finished successfully.
        /// When that happens, this method will return with <see cref="AuthenticationResult"/>.
        /// </summary>
        /// <returns>With <see cref="AuthenticationResult"/> or will throw an <see cref="Exception"/> if a problem occurred during the authentication process.</returns>
        public async Task <AuthenticationResult> SignIn()
        {
            AuthenticationResult authResult;
            var app = PublicClientApp;

            var accounts = await app.GetAccountsAsync();

            var firstAccount = accounts.FirstOrDefault();

            try
            {
                authResult = await app.AcquireTokenSilent(Scopes, firstAccount).ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                // A MsalUiRequiredException happened on AcquireTokenSilent.
                // This indicates you need to call AcquireTokenInteractive to acquire a token
                System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

                try
                {
                    var swvo = new SystemWebViewOptions();
                    if (AuthSettings.BrowserRedirectSuccess != null)
                    {
                        swvo.BrowserRedirectSuccess = AuthSettings.BrowserRedirectSuccess;
                    }
                    if (AuthSettings.BrowserRedirectError != null)
                    {
                        swvo.BrowserRedirectError = AuthSettings.BrowserRedirectError;
                    }
                    authResult = await app.AcquireTokenInteractive(Scopes).WithAccount(accounts.FirstOrDefault()).WithPrompt(Prompt.SelectAccount).WithSystemWebViewOptions(swvo).ExecuteAsync();
                }
                catch (MsalException msalex)
                {
                    System.Diagnostics.Debug.WriteLine($"Error Acquiring Token: {System.Environment.NewLine}{msalex}");
                    throw;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Error Acquiring Token Silently: {System.Environment.NewLine}{ex}");
                throw;
            }
            return(authResult);
        }
Example #10
0
        public static async Task SignInAsync()
        {
            try
            {
                if (App.CurrentAccount == null)
                {
                    var accounts = await App.ClientApplication.GetAccountsAsync();

                    App.CurrentAccount = accounts.FirstOrDefault();
                }

                App.AuthResult = await App.ClientApplication
                                 .AcquireTokenSilent(Constants.Scopes, App.CurrentAccount)
                                 .ExecuteAsync();
            }
            catch (MsalUiRequiredException)
            {
                var interactiveRequest = App.ClientApplication
                                         .AcquireTokenInteractive(Constants.Scopes)
                                         .WithParentActivityOrWindow(App.AuthUIParent);
                var systemWebViewOptions = new SystemWebViewOptions()
                {
                    iOSHidePrivacyPrompt = true
                };
                interactiveRequest.WithSystemWebViewOptions(systemWebViewOptions);
                interactiveRequest.WithUseEmbeddedWebView(false);

                if (App.AuthUIParent != null)
                {
                    interactiveRequest = interactiveRequest
                                         .WithParentActivityOrWindow(App.AuthUIParent);
                }

                App.AuthResult = await interactiveRequest.ExecuteAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Authentication failed. See exception messsage for more details: " + ex.Message);
            }
        }
Example #11
0
        public void ValidateInteractiveParameters(
            WebViewPreference expectedEmbeddedWebView,
            IAccount expectedAccount = null,
            IEnumerable <string> expectedExtraScopesToConsent = null,
            string expectedLoginHint            = null,
            string expectedPromptValue          = null,
            ICustomWebUi expectedCustomWebUi    = null,
            SystemWebViewOptions browserOptions = null)
        {
            Assert.IsNotNull(InteractiveParametersReceived);

            Assert.AreEqual(expectedAccount, InteractiveParametersReceived.Account);
            CoreAssert.AreScopesEqual(
                (expectedExtraScopesToConsent ?? new List <string>()).AsSingleString(),
                InteractiveParametersReceived.ExtraScopesToConsent.AsSingleString());
            Assert.AreEqual(expectedLoginHint, InteractiveParametersReceived.LoginHint);
            Assert.AreEqual(expectedPromptValue ?? Prompt.NotSpecified.PromptValue, InteractiveParametersReceived.Prompt.PromptValue);
            Assert.IsNotNull(InteractiveParametersReceived.UiParent);
            Assert.AreEqual(expectedEmbeddedWebView, InteractiveParametersReceived.UseEmbeddedWebView);
            Assert.AreEqual(expectedCustomWebUi, InteractiveParametersReceived.CustomWebUi);
            Assert.AreEqual(browserOptions, InteractiveParametersReceived.UiParent.SystemWebViewOptions);
        }
        public static async Task <AuthenticationResult> TryLogin(string applicationClientId, Scope scope, Func <IEnumerable <IAccount>, Task <IAccount> > selectAccount, CancellationToken cancelToken, string tenantID = defaultTenant, string redirectURI = defaultRedirect)
        {
            string[] PrimaryScopes = null;
            string[] ExtraScopes   = null;
            switch (scope)
            {
            case Scope.ARR:
                PrimaryScopes = arrScopes;
                ExtraScopes   = storageScopes;
                break;

            case Scope.Storage:
                PrimaryScopes = storageScopes;
                ExtraScopes   = arrScopes;
                break;
            }

            var clientApplication       = GetClientApp(applicationClientId, tenantID, redirectURI);
            AuthenticationResult result = null;

            try
            {
                var accounts = await clientApplication.GetAccountsAsync();

                if (accounts.Any() && selectedAccount == null)
                {
                    selectedAccount = await selectAccount(accounts);

                    //Clean up any accounts not selected (all accounts if none selected)
                    foreach (var account in accounts)
                    {
                        if (account == selectedAccount)
                        {
                            continue;
                        }
                        await clientApplication.RemoveAsync(account);
                    }
                }

                if (selectedAccount != null)
                {
                    result = await clientApplication.AcquireTokenSilent(PrimaryScopes, selectedAccount).ExecuteAsync();

                    return(result);
                }
                else
                {
                    try
                    {
#if UNITY_EDITOR
                        var options = new SystemWebViewOptions()
                        {
                            HtmlMessageError   = "<p> An error occured: {0}. Details {1} </p>",
                            HtmlMessageSuccess = "<p> Success! You may now close this browser. </p>"
                        };
                        result = await clientApplication.AcquireTokenInteractive(PrimaryScopes).WithExtraScopesToConsent(ExtraScopes).WithUseEmbeddedWebView(false).WithSystemWebViewOptions(options).ExecuteAsync(cancelToken);
#else
                        result = await clientApplication.AcquireTokenInteractive(PrimaryScopes).WithExtraScopesToConsent(ExtraScopes).WithUseEmbeddedWebView(true).ExecuteAsync(cancelToken);
#endif
                    }
                    catch (MsalUiRequiredException ex)
                    {
                        Debug.LogError("MsalUiRequiredException");
                        Debug.LogException(ex);
                    }
                    catch (MsalServiceException ex)
                    {
                        Debug.LogError("MsalServiceException");
                        Debug.LogException(ex);
                    }
                    catch (MsalClientException ex)
                    {
                        Debug.LogError("MsalClientException");
                        Debug.LogException(ex);
                        // Mitigation: Use interactive authentication
                    }
                    catch (Exception ex)
                    {
                        Debug.LogError("Exception");
                        Debug.LogException(ex);
                    }

                    selectedAccount = result.Account;

                    return(result);
                }
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);

                Debug.LogError("Exception using cached credentials, clearing cache");
                //Clear the cache file if there's an exception using the cache
                if (File.Exists(AADTokenCache.CacheFilePath))
                {
                    File.Delete(AADTokenCache.CacheFilePath);
                }
            }

            return(null);
        }
        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. Confidential Client
                        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:
                        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 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 #14
0
 private DefaultOsBrowserWebUi CreateTestWebUI(SystemWebViewOptions options = null)
 {
     return(new DefaultOsBrowserWebUi(_platformProxy, _logger, options, _tcpInterceptor));
 }
        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
                       11. AcquireTokenForClient with multiple threads
                        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(GraphAppScope)
                                          //.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 11:     // AcquireTokenForClient with multiple threads
                        Console.Write("Enter number of threads to start (default 10): ");
                        int totalThreads = int.TryParse(Console.ReadLine(), out totalThreads) ? totalThreads : 10;
                        Console.Write("Enter run duration in seconds (default 10): ");
                        int durationInSeconds = int.TryParse(Console.ReadLine(), out durationInSeconds) ? durationInSeconds : 10;

                        var acquireTokenBuilder = CreateCca().AcquireTokenForClient(GraphAppScope);

                        var threads = new List <Thread>();
                        for (int i = 0; i < totalThreads; i++)
                        {
                            var thread = new Thread(new ThreadStart(new ThreadWork(i, acquireTokenBuilder, durationInSeconds).Run));
                            thread.Name = $"Thread #{i}";
                            threads.Add(thread);
                        }

                        foreach (var thread in threads)
                        {
                            thread.Start();
                        }

                        foreach (var thread in threads)
                        {
                            thread.Join();
                        }

                        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 #16
0
        public static async Task Main(string[] args)
        {
            string[] scopes = { UserReadScope };

            AuthenticationResult result;

            if (UseWam)
            {
                result = await CreateAppBuilder()
                         .Build()
                         .AcquireTokenInteractive(scopes)
                         .ExecuteAsync();
            }
            else if (HasWebView2(out string runtimePath))
            {
                var webView2Options = new WebView2Options
                {
                    Title = "Hello, World!",
                    BrowserExecutableFolder = runtimePath
                };

                result = await CreateAppBuilder()
                         .Build()
                         .AcquireTokenInteractive(scopes)
                         .WithUseEmbeddedWebView(true)
                         .WithWebView2Options(webView2Options)
                         .ExecuteAsync();
            }
            else if (HasLegacyWebView())
            {
                result = await CreateAppBuilder()
                         .Build()
                         .AcquireTokenInteractive(scopes)
                         .WithUseEmbeddedWebView(true)
                         .ExecuteAsync();
            }

            else if (RedirectUri.IsLoopback) // System webview requires loopback redirect
            {
                var systemWebViewOptions = new SystemWebViewOptions
                {
                    HtmlMessageSuccess = "It worked! :)",
                    HtmlMessageError   = "It failed! :(",
                };

                result = await CreateAppBuilder()
                         .WithRedirectUri(RedirectUri.ToString())
                         .Build()
                         .AcquireTokenInteractive(scopes)
                         .WithUseEmbeddedWebView(false)
                         .WithSystemWebViewOptions(systemWebViewOptions)
                         .ExecuteAsync();
            }
            else // Fall back to device code flow
            {
                result = await CreateAppBuilder()
                         .Build()
                         .AcquireTokenWithDeviceCode(scopes, WriteDeviceCode)
                         .ExecuteAsync();
            }

            Console.WriteLine(result.AccessToken);
        }