无法使用.WithPrompt(Prompt.SelectAccount)打开提示

问题描述 投票:0回答:1

我正在我的 Windows 应用程序中实现 MSAL。我想打开一个 Windows 提示来打开以选择帐户。 当我将鼠标悬停在代码中的提示上时,我看到以下错误

提示根本打不开。

下面是我正在使用的代码

    private async Task CallGraph()
        {
            var _clientApp = PublicClientApplicationBuilder.Create(id)
                .WithAuthority(AzureCloudInstance.AzurePublic, "somevalue")
                .WithDefaultRedirectUri()
                .Build();
            string[] scopes = new string[] { "user.read" };
            AuthenticationResult authResult = null;
            var app = _clientApp;
            //ResultText.Text = string.Empty;
            //TokenInfoText.Text = string.Empty;

            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
                {                   
                    authResult = await app.AcquireTokenInteractive(scopes)
                    //.WithUseEmbeddedWebView(false)
                    //.WithPrompt(Prompt.SelectAccount)
                    .ExecuteAsync();                   
                }
                catch (MsalException msalex)
        {

            TraceLogging.LogException($"Error Acquiring Token:{System.Environment.NewLine}{msalex}", ex);


        }
    }
    catch (Exception ex)
    {
        TraceLogging.LogException($"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}", ex);
        return;
    }

   

 if (authResult != null)
    {
        await GetHttpContentWithToken(graphAPIEndpoint, authResult.AccessToken);
        string res = $"Username: {authResult.Account.Username}" + Environment.NewLine;
        //DisplayBasicTokenInfo(authResult);
        //this.SignOutButton.Visibility = 

Visibility.Visible;
            }

            }
            public async Task<string> GetHttpContentWithToken(string url, string token)
        {
            var httpClient = new System.Net.Http.HttpClient();
            System.Net.Http.HttpResponseMessage response;
            try
            {
                var request = new 

System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
                //Add the token in Authorization header
                request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                response = await httpClient.SendAsync(request);
                var content = await response.Content.ReadAsStringAsync();
                return content;
            }

   

 catch (Exception ex)
    {
        return ex.ToString();
    }
}

我想为桌面和 Web 应用程序实现 msal。请告诉我更多详细信息或任何使用 asp .net 而不是 dotnet core 的示例应用程序

azure desktop-application prompt azure-authentication msal
1个回答
0
投票

我通过在移动和桌面应用程序平台中添加重定向URI启用公共客户端流来注册一个Azure AD应用程序:

enter image description here

现在,我创建了一个 Windows 窗体应用程序(.NET Framework),并用以下代码替换了以下文件:

Form1.cs

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

namespace GraphApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load; // Subscribe to the Form Load event
        }

        private async void Form1_Load(object sender, EventArgs e)
        {
            // Add any initialization code here if needed
        }

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

        private static async Task CallGraph()
        {
            var clientId = "appId";
            var _clientApp = PublicClientApplicationBuilder.Create(clientId)
                .WithAuthority(AzureCloudInstance.AzurePublic, "tenantId")
                .WithDefaultRedirectUri()
                .Build();
            string[] scopes = new string[] { "user.read" };
            AuthenticationResult authResult = null;
            var app = _clientApp;

            var accounts = await app.GetAccountsAsync();
            var firstAccount = accounts.FirstOrDefault();

            try
            {
                authResult = await app.AcquireTokenSilent(scopes, firstAccount)
                    .ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

                try
                {
                    authResult = await app.AcquireTokenInteractive(scopes)
                        .WithPrompt(Prompt.SelectAccount)
                        .ExecuteAsync();
                }
                catch (MsalException msalex)
                {
                    Trace.WriteLine($"Error Acquiring Token:{Environment.NewLine}{msalex}");
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"Error Acquiring Token Silently:{Environment.NewLine}{ex}");
                return;
            }

            if (authResult != null)
            {
                MessageBox.Show($"Username: {authResult.Account.Username}");
            }
        }
    }
}

Form1.Designer.cs

namespace GraphApp
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(102, 90);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "Call Graph";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button button1;
    }
}

当我现在运行应用程序并单击 Call Graph 按钮时,会提示选择一个帐户,如下所示:

enter image description here

登录时,它要求我同意以下屏幕的权限:

enter image description here

接受同意后,我成功弹出带有登录用户的用户名的弹出窗口,如下所示:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.