IPublicClientApplication GetAccountsAsync returns Windows Forms App 中没有任何内容

IPublicClientApplication GetAccountsAsync returns nothing in Windows Forms App

我正尝试在 https://cmatskas.com/modern-authentication-with-azure-ad-for-winforms-native-apps-2/ 工作时提供示例应用程序。

我在 Azure 中注册了应用程序并获得了客户端 ID 和租户 ID。这两个 ID 都是类似 GUID 的数字。这些代码已替换到程序中。

我还在 Form1 中添加了一个多行文本框 txtLog 来显示进度消息。

以下程序不return帐户:

private async Task<AuthenticationResult> Login()
{

AuthenticationResult authResult = null;
var accounts = await Program.PublicClientApp.GetAccountsAsync();
txtLog.Text += "accounts count " + accounts.ToArray().Count().ToString() + "\r\n";

if (accounts != null)
{ label2.Text += $"GetAccountsAsync passed!"; }
else
{ label2.Text += "PublicClientApp.GetAccountsAsync returned an empty list"; }


var firstAccount = accounts.FirstOrDefault();

if (firstAccount != null)
{ label2.Text += firstAccount.Username; }
else
{ label2.Text += "firstAccount is null"; }


try
{
authResult = await Program.PublicClientApp.AcquireTokenSilent(scopes, firstAccount)
    .ExecuteAsync();
    label2.Text = "Auth result passed!";
}
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}");
            label2.Text += $"Auth result error: {ex.Message}";

            try
            {
                authResult = await Program.PublicClientApp.AcquireTokenInteractive(scopes)
                    .WithAccount(accounts.FirstOrDefault())
                    .WithPrompt(Prompt.SelectAccount)
                    .ExecuteAsync();
                txtLog.Text += "authResult AccessToken: " + authResult.AccessToken + "\r\n";
                label2.Text += "AcquireTokenInteractive passed";
            }
            catch (MsalException msalex)
            {
                label1.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
            }
        }
        catch (Exception ex)
        {
            label1.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
        }
        return authResult;
    }


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Identity.Client;

namespace Modern2
{
    static class Program
    {

    public static string ClientId = "1189b025-e4c7-4265-b3fb-a03e15582165";
    public static string Tenant = "223591c8-866c-485c-b6db-35e7d2527da7";

    //public static string ClientId = Environment.GetEnvironmentVariable("ClientId", EnvironmentVariableTarget.User);
    //public static string Tenant = Environment.GetEnvironmentVariable("Tenant", EnvironmentVariableTarget.User);
    private static IPublicClientApplication clientApp;

    public static Form1 goFrmMain;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        goFrmMain = new Form1();
        goFrmMain.txtLog.Text = "";
        InitializeAuth();
        Application.Run(goFrmMain);
    }
    public static IPublicClientApplication PublicClientApp { get { return clientApp; } }

    private static void InitializeAuth()
    {

        clientApp = PublicClientApplicationBuilder.Create(ClientId)
                .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
                .WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
                .Build();
        goFrmMain.txtLog.Text += "clientApp.Authority: " + clientApp.Authority + "\r\n";
        TokenCacheHelper.EnableSerialization(clientApp.UserTokenCache);
        goFrmMain.txtLog.Text += "TokenCacheHelper.CacheFilePath: " + TokenCacheHelper.CacheFilePath + "\r\n";
    }
}

}

Azure 中的公司目录是未托管的。

https://docs.microsoft.com/en-us/azure/active-directory/enterprise-users/domains-admin-takeover 中的“在 Azure Active Directory 中以管理员身份接管非托管目录”的步骤实施后,该功能开始返回帐户。