提问者:小点点

如何使用图形API在Windows窗体应用程序中显示日志用户名?


我正在使用图形API创建一个Windows窗体应用程序。在应用上,我有更多的形式。另外,我有一个用于登录用户的函数,当用户登录时,他的名字会写在第一个表单上的标签上。在其他表单上,我有一个取消按钮,所以当用户单击取消按钮时,第一个表单会出现,但用户名不会写在标签上。代码如下:

public static class GraphHelper
{
    private static string[] scopes = new string[] { "user.read" };
    public static string TokenForUser = null;
    public static DateTimeOffset expiration;

    private const string ClientId = "599ed98d-4356-4a96-ad37-04391e9c48dc";

    private const string Tenant = "common"; 
    private const string Authority = "https://login.microsoftonline.com/" + Tenant;

    // The MSAL Public client app
    private static IPublicClientApplication PublicClientApp;

    private static string MSGraphURL = "https://graph.microsoft.com/beta/";
    private static AuthenticationResult authResult;

    public static GraphServiceClient graphClient;
    public static string token;

    public static GraphServiceClient GetGraphClient(string token)
    {
        if (graphClient == null)
        {
            // Create Microsoft Graph client.
            try
            {
                graphClient = new GraphServiceClient(
                    "https://graph.microsoft.com/beta",
                    new DelegateAuthenticationProvider(
                        async (requestMessage) =>
                        {
                            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
                            // This header has been added to identify our sample in the Microsoft Graph service.  If extracting this code for your project please remove.
                            requestMessage.Headers.Add("SampleID", "uwp-csharp-snippets-sample");

                        }));
                return graphClient;
            }

            catch (Exception ex)
            {
                Debug.WriteLine("Could not create a graph client: " + ex.Message);
            }
        }
        return graphClient;
    }

    public static async Task<string> GetTokenForUserAsync()
    {
        if (TokenForUser == null || expiration <= DateTimeOffset.UtcNow.AddMinutes(10))
        {
            PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
          .WithAuthority(Authority)
          .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
           .WithLogging((level, message, containsPii) =>
           {
               Debug.WriteLine($"MSAL: {level} {message} ");
           }, LogLevel.Warning, enablePiiLogging: false, enableDefaultPlatformLogging: true)
          .Build();

            // It's good practice to not do work on the UI thread, so use ConfigureAwait(false) whenever possible.
            IEnumerable<IAccount> accounts = await PublicClientApp.GetAccountsAsync().ConfigureAwait(false);
            IAccount firstAccount = accounts.FirstOrDefault();

            try
            {
                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
                Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

                authResult = await PublicClientApp.AcquireTokenInteractive(scopes)
                                                  .ExecuteAsync()
                                                  .ConfigureAwait(false);
            }

            TokenForUser = authResult.AccessToken;
        }

        return TokenForUser;
    }

    public static async Task<User> GetMeAsync(string token)
    {
        graphClient = GetGraphClient(token);
        try
        {
            // GET /me
            return await graphClient.Me
                .Request()
                .Select(u => new
                {
                    u.DisplayName
                })
                .GetAsync();
        }
        catch (ServiceException ex)
        {
            return null;
        }
    }
}

  public partial class Form1 : Form
{
    public static string token;
    public static GraphServiceClient graphClient;

    public Form1()
    {
        InitializeComponent();
    }

    private async void button1_Click(object sender, EventArgs e)
    {
        token = await GraphHelper.GetTokenForUserAsync();
        User graphUser = await GraphHelper.GetMeAsync(token);
        label4.Text = graphUser.DisplayName;
    }
}

public partial class Form2 : Form
{

    public Form2()
    {
        InitializeComponent();
    }
private void button2_Click(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();
        this.Close();
        f1.Show();
    }
}

有没有人知道当用户单击“取消”按钮时,如何在第一个表单上显示用户名?


共1个答案

匿名用户

form1中创建一个公共方法,该方法将调用Graph API并显示用户名。

Form1.Button1_ClickForm2.Button2_Click调用此方法

public partial class Form1 : Form
{
    public static string token;
    public static GraphServiceClient graphClient;

    public Form1()
    {
        InitializeComponent();
    }

    private async void button1_Click(object sender, EventArgs e)
    {
        await ShowUserAsync();
    }

    public async Task ShowUserAsync()
    {
        token = await GraphHelper.GetTokenForUserAsync();
        User graphUser = await GraphHelper.GetMeAsync(token);
        label4.Text = graphUser.DisplayName;
    }
}

public partial class Form2 : Form
{

    public Form2()
    {
        InitializeComponent();
    }
    private async void button2_Click(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();
        await f1.ShowUserAsync();
        this.Close();
        f1.Show();
    }
}