Пример #1
0
        public async Task LogoutAsync()
        {
            try
            {
                var accounts = await _client.GetAccountsAsync();

                var account = accounts.FirstOrDefault();
                if (account != null)
                {
                    await _client.RemoveAsync(account);
                }

                _authenticationResult = null;
                LoggedOut?.Invoke(this, EventArgs.Empty);
            }
            catch (MsalException)
            {
                // TODO WTS: LogoutAsync can fail please handle exceptions as appropriate to your scenario
                // For more info on MsalExceptions see
                // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/exceptions
            }
        }
Пример #2
0
        private static async Task <AuthenticationResult> RunRopcAndSilentAsync(
            string logPrefix,
            IPublicClientApplication pca)
        {
            Console.WriteLine($"{logPrefix} Acquiring token by ROPC...");
            var result = await AcquireTokenROPCAsync(pca).ConfigureAwait(false);

            Console.WriteLine($"{logPrefix} OK. Now getting the accounts");
            var accounts = await pca.GetAccountsAsync().ConfigureAwait(false);

            Console.WriteLine($"{logPrefix} Acquiring token silent");

            result = await pca.AcquireTokenSilent(Config.Scopes, accounts.First())
                     .ExecuteAsync()
                     .ConfigureAwait(false);

            Console.WriteLine($"{logPrefix} Deleting the account");
            foreach (var acc in accounts)
            {
                await pca.RemoveAsync(acc).ConfigureAwait(false);
            }

            return(result);
        }
        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;
                    });
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Call AcquireTokenAsync - to acquire a token requiring user to sign-in
        /// </summary>
        internal async static Task <bool> MSALWork(AADAction action)
        {
            OOFSponder.Logger.Info(OOFSponderInsights.CurrentMethod());

            //lock this so we don't get multiple auth prompts
            OOFSponder.Logger.Info("Attempting to enter critical section for auth code");
            await semaphoreSlim.WaitAsync();

            OOFSponder.Logger.Info("Inside critical section for auth code");

            bool _result  = false;
            var  accounts = await PublicClientApp.GetAccountsAsync();

            var firstAccount = accounts.FirstOrDefault();

            try
            {
                if (action == AADAction.SignIn | action == AADAction.ForceSignIn)
                {
                    try
                    {
                        //MSAL 1.0 style - deprecated
                        //authResult = await PublicClientApp.AcquireTokenSilentAsync(_scopes, PublicClientApp.Users.FirstOrDefault());

                        //MSAL 3.0 style
                        authResult = await PublicClientApp.AcquireTokenSilent(_scopes, firstAccount).ExecuteAsync();
                    }
                    catch (MsalUiRequiredException ex)
                    {
                        // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
                        //Don't track this one since it can basically be considered expected.
                        OOFSponder.Logger.Warning(new Exception($"Unable to acquire token silently: ", ex));

                        try
                        {
                            //MSAL 1.0 style
                            //authResult = await PublicClientApp.AcquireTokenAsync(_scopes);

                            //MSAL 3.0 style
                            authResult = await PublicClientApp.AcquireTokenInteractive(_scopes).ExecuteAsync();
                        }
                        catch (MsalException msalex)
                        {
                            OOFSponder.Logger.Error(new Exception($"Error acquiring token interactively: ", msalex));
                        }
                    }
                    catch (Exception ex)
                    {
                        OOFSponder.Logger.Error(new Exception($"Error acquiring token: ", ex));
                        return(false);
                    }

                    //MSAL 1.0 style
                    //if (PublicClientApp.Users.Count() > 0)

                    //MSAL 3.0 style
                    if (authResult != null)
                    {
                        _result = true;

                        //also, update the Application Insights info with the authenticated user
                        //MSAL 1.0 style
                        //OOFSponderInsights.AIClient.Context.User.Id = authResult.User.DisplayableId.Split('@')[0];

                        //MSAL 3.0 style
                        OOFSponderInsights.AIClient.Context.User.Id = authResult.Account.Username;
                    }
                    else
                    {
                        _result = false;
                    }
                }
                else
                {
                    //MSAL 1.0
                    //if (PublicClientApp.Users.Any())

                    //MSAL 3.0
                    if (firstAccount != null)
                    {
                        try
                        {
                            //MSAL 1.0
                            //PublicClientApp.Remove(PublicClientApp.Users.FirstOrDefault());

                            //MSAL 3.0
                            await PublicClientApp.RemoveAsync(firstAccount);

                            _result = true;
                        }
                        catch (MsalException ex)
                        {
                            OOFSponder.Logger.Error(new Exception("Error signing out user: "******"MSAL code failed miserably for user: "******"Leaving critical section for auth code");
                semaphoreSlim.Release();
                OOFSponder.Logger.Info("Left critical section for auth code");
            }

            return(_result);
        }
Пример #5
0
        private async void SignInButton_Click(object sender, RoutedEventArgs e)
        {
            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)
            {
                // clear the cache
                while (accounts.Any())
                {
                    await _app.RemoveAsync(accounts.First());

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

                // Also clear cookies from the browser control.
                SignInButton.Content = SignInString;
                UserName.Content     = UserNotSignedIn;
                return;
            }

            try
            {
                var result = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
                             .ExecuteAsync()
                             .ConfigureAwait(false);

                Dispatcher.Invoke(() =>
                {
                    SignInButton.Content = ClearCacheString;
                    SetUserName(result.Account);
                }
                                  );
            }
            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 result = await _app.AcquireTokenInteractive(Scopes)
                                 .WithAccount(accounts.FirstOrDefault())
                                 .WithPrompt(Prompt.SelectAccount)
                                 .ExecuteAsync()
                                 .ConfigureAwait(false);

                    Dispatcher.Invoke(() =>
                    {
                        SignInButton.Content = ClearCacheString;
                        SetUserName(result.Account);
                    }
                                      );
                }
                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 = UserNotSignedIn; });
                }
            }
        }
Пример #6
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();
            }
        }
        private static async Task RunConsoleAppLogicAsync()
        {
            while (true)
            {
                Console.Clear();

                await DisplayAccountsAsync(s_pcaFam1).ConfigureAwait(false);

                // display menu
                Console.WriteLine(@"
                        1. Acquire Token App1 (family member)
                        2. Acquire Token App2 (family member)
                        3. Acquire Token App3 (non-family member)
                        4. Acquire Token Silent App1 (family member)
                        5. Acquire Token Silent App2 (family member)
                        6. Acquire Token Silent App3 (non-family member)


                        7. Clear cache via App1
                        8. Clear cache via App2
                        0. Exit App
                    Enter your Selection: ");
                int.TryParse(Console.ReadLine(), out var selection);

                Task <AuthenticationResult> authTask = null;

                try
                {
                    switch (selection)
                    {
                    case 1:
                        authTask = StartInteractiveAuthAsync(s_pcaFam1);
                        FetchTokenAsync(s_pcaNonFam, authTask).GetAwaiter().GetResult();
                        break;

                    case 2:
                        authTask = StartInteractiveAuthAsync(s_pcaFam2);
                        FetchTokenAsync(s_pcaNonFam, authTask).GetAwaiter().GetResult();
                        break;

                    case 3:
                        authTask = StartInteractiveAuthAsync(s_pcaNonFam);
                        FetchTokenAsync(s_pcaNonFam, authTask).GetAwaiter().GetResult();
                        break;

                    case 4:
                        authTask = StartSilentAuthAsync(s_pcaFam1);
                        FetchTokenAsync(s_pcaFam1, authTask).GetAwaiter().GetResult();
                        break;

                    case 5:
                        authTask = StartSilentAuthAsync(s_pcaFam2);
                        FetchTokenAsync(s_pcaNonFam, authTask).GetAwaiter().GetResult();
                        break;

                    case 6:
                        authTask = StartSilentAuthAsync(s_pcaNonFam);
                        FetchTokenAsync(s_pcaNonFam, authTask).GetAwaiter().GetResult();
                        break;

                    case 7:
                        var accounts1 = await s_pcaFam1.GetAccountsAsync().ConfigureAwait(false);

                        var accounts2 = await s_pcaFam2.GetAccountsAsync().ConfigureAwait(false);

                        var accounts3 = await s_pcaNonFam.GetAccountsAsync().ConfigureAwait(false);


                        foreach (var acc in accounts1)
                        {
                            await s_pcaFam1.RemoveAsync(acc).ConfigureAwait(false);
                        }

                        break;

                    case 8:
                        accounts1 = await s_pcaFam1.GetAccountsAsync().ConfigureAwait(false);

                        accounts2 = await s_pcaFam2.GetAccountsAsync().ConfigureAwait(false);

                        accounts3 = await s_pcaNonFam.GetAccountsAsync().ConfigureAwait(false);


                        foreach (var acc in accounts2)
                        {
                            await s_pcaFam2.RemoveAsync(acc).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 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();
            }
        }
Пример #9
0
        private static async Task RunConsoleAppLogicAsync()
        {
            while (true)
            {
                Console.Clear();

                await DisplayAccountsAsync(s_pcaFam1).ConfigureAwait(false);

                // display menu
                Console.WriteLine($@"
                        1. Acquire Token App1 (family member)
                        2. Acquire Token App2 (family member)
                        3. Acquire Token App3 (non-family member)
                        4. Acquire Token Silent App1 (family member)
                        5. Acquire Token Silent App2 (family member)
                        6. Acquire Token Silent App3 (non-family member)


                        7. Clear cache via App1
                        8. Clear cache via App2
                        t. Toggle IWA (currently {(s_useIWA ? "ON" : "OFF")})
                        0. Exit App
                    Enter your Selection: ");
                char.TryParse(Console.ReadLine(), out var selection);
                Task <AuthenticationResult> authTask;

                try
                {
                    switch (selection)
                    {
                    case '1':
                        authTask = StartAcquireTokenAsync(s_pcaFam1);
                        FetchTokenAsync(s_pcaNonFam, authTask).GetAwaiter().GetResult();
                        break;

                    case '2':
                        authTask = StartAcquireTokenAsync(s_pcaFam2);
                        FetchTokenAsync(s_pcaNonFam, authTask).GetAwaiter().GetResult();
                        break;

                    case '3':
                        authTask = StartAcquireTokenAsync(s_pcaNonFam);
                        FetchTokenAsync(s_pcaNonFam, authTask).GetAwaiter().GetResult();
                        break;

                    case '4':
                        authTask = StartSilentAuthAsync(s_pcaFam1);
                        FetchTokenAsync(s_pcaFam1, authTask).GetAwaiter().GetResult();
                        break;

                    case '5':
                        authTask = StartSilentAuthAsync(s_pcaFam2);
                        FetchTokenAsync(s_pcaNonFam, authTask).GetAwaiter().GetResult();
                        break;

                    case '6':
                        authTask = StartSilentAuthAsync(s_pcaNonFam);
                        FetchTokenAsync(s_pcaNonFam, authTask).GetAwaiter().GetResult();
                        break;

                    case '7':
                        var accounts1 = await s_pcaFam1.GetAccountsAsync().ConfigureAwait(false);

                        var accounts2 = await s_pcaFam2.GetAccountsAsync().ConfigureAwait(false);

                        var accounts3 = await s_pcaNonFam.GetAccountsAsync().ConfigureAwait(false);


                        foreach (var acc in accounts1)
                        {
                            await s_pcaFam1.RemoveAsync(acc).ConfigureAwait(false);
                        }

                        break;

                    case '8':
                        accounts1 = await s_pcaFam1.GetAccountsAsync().ConfigureAwait(false);

                        accounts2 = await s_pcaFam2.GetAccountsAsync().ConfigureAwait(false);

                        accounts3 = await s_pcaNonFam.GetAccountsAsync().ConfigureAwait(false);


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

                        break;

                    case '0':
                        return;

                    case 't':
                        s_useIWA = true;
                        break;

                    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();
            }
        }
Пример #10
0
        public async Task <AuthenticateResponse> AzureSingleSignOn()
        {
            string clientId    = ConfigurationManager.AppSettings["aad:clientId"];
            string tenantId    = ConfigurationManager.AppSettings["aad:tenantId"];
            string aadInstance = ConfigurationManager.AppSettings["aad:aadInstance"];

            string[] scopes = ConfigurationManager.AppSettings["aad:scopes"].Split(new[] { ',' }); //"user.read"

            string authority = String.Format(CultureInfo.InvariantCulture, "{0}{1}", aadInstance, tenantId);

            app = PublicClientApplicationBuilder
                  .Create(clientId)
                  .WithDefaultRedirectUri()
                  .WithAuthority(authority)
                  .Build();
            //this enables the cache to be saved to a file in the clients install directory
            TokenCacheHelper.EnableSerialization(app.UserTokenCache);
            //AuthenticationResult authenticationResult = new AuthenticationResult("00", false, "00", DateTimeOffset.MinValue, DateTimeOffset.MinValue, "00", null, "", new[] { "" }, Guid.Empty);
            AuthenticateResponse response = null;
            AuthenticationResult authRes  = null;

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

                if (accounts.Any())
                {
                    account = accounts.FirstOrDefault();
                    authRes = await app.AcquireTokenSilent(scopes, account).ExecuteAsync();
                }
                else
                {
                    authRes = await app.AcquireTokenSilent(scopes, System.Security.Principal.WindowsIdentity.GetCurrent().Name).ExecuteAsync();
                }

                if (authRes.Account != null)
                {
                    response      = SetAuthenticationResponse(authRes);
                    response.Meta = new System.Collections.Generic.Dictionary <string, string>();
                    response.Meta.Add("token", authRes.IdToken);
                    response.Meta.Add("secret", authRes.AccessToken);
                    return(response);
                }
            }
            catch (MsalUiRequiredException ax)
            {
                try
                {
                    if (ax.ErrorCode == MsalError.FailedToAcquireTokenSilentlyFromBroker || ax.ErrorCode == MsalError.NoAccountForLoginHint || ax.ErrorCode == MsalError.CodeExpired)
                    {
                        authRes = await app.AcquireTokenInteractive(scopes).ExecuteAsync();

                        response = SetAuthenticationResponse(authRes);
                        return(response);
                    }
                    else
                    {
                    }
                }
                catch (MsalClientException icx)
                {
                    Logger.Info("Login:"******"Login:"******"Login:", ex);
                if (account != null)
                {
                    await app.RemoveAsync(account);
                }
            }
            return(null);
        }
 public async Task DeleteCachedAccount()
 {
     await msalClient.RemoveAsync(account);
 }
        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();
            }
        }
Пример #13
0
        private static async Task RunConsoleAppLogicAsync()
        {
            while (true)
            {
                Console.Clear();

                Console.WriteLine("Authority: " + GetAuthority());
                await DisplayAccountsAsync(s_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 Default System Browser)
                        5. Acquire Token Silently
                        6. Confidential Client with Certificate (needs extra config)
                        7. Clear cache
                        8. 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 = s_pca.AcquireTokenByIntegratedWindowsAuth(s_scopes).WithUsername(s_username).ExecuteAsync(CancellationToken.None);
                        await FetchTokenAndCallGraphAsync(s_pca, authTask).ConfigureAwait(false);

                        break;

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

                        break;

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

                        break;

                    case 4: // acquire token interactive

                        authTask = s_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(s_pca, authTask).ConfigureAwait(false);

                        break;

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

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

                        break;

                    case 6:
                        RunClientCredentialWithCertificate();
                        break;

                    case 7:
                        var accounts = await s_pca.GetAccountsAsync().ConfigureAwait(false);

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

                        break;

                    case 8:

                        s_currentTid = (s_currentTid + 1) % s_tids.Length;
                        s_pca        = CreatePca();

                        RunConsoleAppLogicAsync().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();
            }
        }
Пример #14
0
        public static async Task SingOutMSGraphAccount(IAccount firstAccount)
        {
            SetProperty(ref UserSignedOut, false);

            await publicClientApp.RemoveAsync(firstAccount).ConfigureAwait(false);
        }
        private async void SignIn(object sender = null, RoutedEventArgs args = null)
        {
            var accounts = (await _app.GetAccountsAsync()).ToList();

            if (SignInButton.Content.ToString() == ClearCacheString)
            {
                TodoList.ItemsSource = string.Empty;

                // clear the cache
                while (accounts.Any())
                {
                    LoginHint = accounts.First().Username;
                    await _app.RemoveAsync(accounts.First());

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

                // Also clear cookies from the browser control.
                SignInButton.Content = SignInString;
                UserName.Content     = Properties.Resources.UserNotSignedIn;
                return;
            }

            //}

            //
            // Get an access token to call the To Do list service.
            //
            AuthenticationResult result = null;

            try
            {
                if (String.IsNullOrEmpty(LoginHint))
                {
                    result = await _app.AcquireTokenInteractive(Scopes).ExecuteAsync().ConfigureAwait(false);
                }
                else
                {
                    result = await _app.AcquireTokenInteractive(Scopes).WithPrompt(Prompt.ForceLogin).WithLoginHint(LoginHint).ExecuteAsync().ConfigureAwait(false);
                }
                Dispatcher.Invoke(() =>
                {
                    SignInButton.Content = ClearCacheString;
                    this.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;
                }
                                  );
            }
        }
Пример #16
0
        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;
                FileCache.Clear();

                while (accounts.Any())
                {
                    await _app.RemoveAsync(accounts.First());

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

                // Also clear cookies from the browser control.
                SignInButton.Content = signInString;
                UserName.Content     = Properties.Resources.UserNotSignedIn;
                return;
            }

            //
            // Get an access token to call the To Do list service.
            //
            AuthenticationResult result = null;

            try
            {
                // Force a sign-in (PromptBehavior.Always), as the ADAL web browser might contain cookies for the current user, and using .Auto
                // would re-sign-in the same user
                result = await _app.AcquireTokenInteractive(scopes).ExecuteAsync();

                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);
                }

                UserName.Content = Properties.Resources.UserNotSignedIn;

                return;
            }
        }
        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();
            }
        }
        private async Task <AuthenticationResult> KerberosRunTestForUserAsync(
            LabResponse labResponse,
            KerberosTicketContainer ticketContainer)
        {
            HttpSnifferClientFactory factory = null;
            IPublicClientApplication pca     = PublicClientApplicationBuilder
                                               .Create(labResponse.App.AppId)
                                               .WithRedirectUri(SeleniumWebUI.FindFreeLocalhostRedirectUri())
                                               .WithAuthority(labResponse.Lab.Authority + "common")
                                               .WithTestLogging(out factory)
                                               .WithTenantId(labResponse.Lab.TenantId)
                                               .WithClientId(TestConstants.KerberosTestApplicationId)
                                               .WithKerberosTicketClaim(TestConstants.KerberosServicePrincipalName, ticketContainer)
                                               .Build();

            var userCacheAccess = pca.UserTokenCache.RecordAccess();

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

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

            KerberosSupplementalTicket ticket = TestCommon.GetValidatedKerberosTicketFromAuthenticationResult(
                result,
                ticketContainer,
                labResponse.User.Upn);

            Assert.IsNotNull(ticket);

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

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

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

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

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

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

            userCacheAccess.AssertAccessCounts(2, 3);
            AssertCcsRoutingInformationIsSent(factory, labResponse);
            ticket = TestCommon.GetValidatedKerberosTicketFromAuthenticationResult(
                result,
                ticketContainer,
                labResponse.User.Upn);
            Assert.IsNotNull(ticket);

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

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

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

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

            ticket = TestCommon.GetValidatedKerberosTicketFromAuthenticationResult(
                result,
                ticketContainer,
                labResponse.User.Upn);
            Assert.IsNotNull(ticket);

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

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

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

            ticket = TestCommon.GetValidatedKerberosTicketFromAuthenticationResult(
                result,
                ticketContainer,
                labResponse.User.Upn);
            Assert.IsNotNull(ticket);
            TestCommon.ValidateKerberosWindowsTicketCacheOperation(ticket);

            return(result);
        }
Пример #19
0
        private static async Task RunConsoleAppLogicAsync()
        {
            while (true)
            {
                Console.Clear();

                await DisplayAllAccountsAsync().ConfigureAwait(false);

                // display menu
                Console.WriteLine(@"
                        1. Acquire Token App1 (public cloud)
                        2. Acquire Token App2 (Germany cloud)
                        3. Acquire Token App3 (China cloud)
                        4. Acquire Token Silent App1 (public cloud)
                        5. Acquire Token Silent App2 (Germany cloud)
                        6. Acquire Token Silent App3 (China cloud)


                        7. Clear cache
                        0. Exit App
                    Enter your Selection: ");
                int.TryParse(Console.ReadLine(), out var selection);

                Task <AuthenticationResult> authTask = null;

                try
                {
                    switch (selection)
                    {
                    case 1:
                        FetchTokenAsync(
                            s_publicCloudApp,
                            s_publicCloudApp.AcquireTokenInteractive(s_scopesPublicCloud).ExecuteAsync())
                        .GetAwaiter().GetResult();
                        break;

                    case 2:
                        FetchTokenAsync(
                            s_deCloudApp,
                            s_deCloudApp.AcquireTokenInteractive(s_scopesDeCloud).ExecuteAsync())
                        .GetAwaiter().GetResult();
                        break;

                    case 3:
                        FetchTokenAsync(
                            s_cnCloudApp,
                            s_cnCloudApp.AcquireTokenInteractive(s_scopesCnCloud).ExecuteAsync())
                        .GetAwaiter().GetResult();
                        break;

                    case 4:
                        authTask = GetSilentAuthTaskAsync(s_publicCloudApp, s_scopesPublicCloud);
                        FetchTokenAsync(s_publicCloudApp, authTask).GetAwaiter().GetResult();
                        break;

                    case 5:
                        authTask = GetSilentAuthTaskAsync(s_deCloudApp, s_scopesDeCloud);
                        FetchTokenAsync(s_cnCloudApp, authTask).GetAwaiter().GetResult();
                        break;

                    case 6:
                        authTask = GetSilentAuthTaskAsync(s_cnCloudApp, s_scopesCnCloud);
                        FetchTokenAsync(s_cnCloudApp, authTask).GetAwaiter().GetResult();
                        break;

                    case 7:
                        var accountsPublic = await s_publicCloudApp.GetAccountsAsync().ConfigureAwait(false);

                        var accountsDe = await s_deCloudApp.GetAccountsAsync().ConfigureAwait(false);

                        var accountsCn = await s_cnCloudApp.GetAccountsAsync().ConfigureAwait(false);

                        foreach (var acc in accountsPublic)
                        {
                            await s_publicCloudApp.RemoveAsync(acc).ConfigureAwait(false);
                        }
                        foreach (var acc in accountsDe)
                        {
                            await s_deCloudApp.RemoveAsync(acc).ConfigureAwait(false);
                        }
                        foreach (var acc in accountsCn)
                        {
                            await s_cnCloudApp.RemoveAsync(acc).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 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. Acquire SSH Cert Interactive
                        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 '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':     // 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 '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();
                        RunConsoleAppLogicAsync(pca).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();
            }
        }
        public void ExpireAccessToken(Dictionary<string, string> input)
        {
            EnsurePublicClientApplication(input);

            _publicClientApplication.RemoveAsync(CurrentUser);
        }