ExecuteAsync 不 return 控制调试器

ExecuteAsync doesn't return control to the debugger

我正在尝试使用 MSAL.NET 获取令牌,并且我几乎都在使用开箱即用的教程代码。

using Microsoft.Identity.Client;
using MyApp.Interfaces;
using System;
using System.Threading.Tasks;

namespace MyApp.NetworkServices
{
    public class MyAuthorizationClient : IMyAuthorizationClient
    {
        private readonly string[] _resourceIds;
        private IConfidentialClientApplication App;

        public MyAuthorizationClient(IMyAuthenticationConfig MyAuthenticationConfig)
        {
            _resourceIds = new string[] { MyAuthenticationConfig.MyApimResourceID };

            App = ConfidentialClientApplicationBuilder.Create(MyAuthenticationConfig.MyApimClientID)
                .WithClientSecret(MyAuthenticationConfig.MyApimClientSecret)
                .WithAuthority(new Uri(MyAuthenticationConfig.Authority))
                .Build();
        }

        public async Task<AuthenticationResult> GetMyAccessTokenResultAsync()
        {
            AuthenticationResult result = null;

            try
            {
                result = await App.AcquireTokenForClient(_resourceIds).ExecuteAsync().ConfigureAwait(continueOnCapturedContext:false);
            }
            catch(MsalClientException ex)
            {
                ...
            }
            return result;            
    }
}

}

我遇到的问题是,在 await 调用中,它从来没有 returns。调试器不恢复控制,应用程序进入前台,就好像它继续 运行。我无法查询 result 的结果,并且我已经将 await 配置为不继续。

我查看了这个很棒的线程,但它没有为我的场景提供任何解决方案:

您的代码:

try
{
    result = await App.AcquireTokenForClient(_resourceIds).ExecuteAsync().ConfigureAwait(continueOnCapturedContext:false);
}

删除 await 并使用 .Result 而不是 .ConfigureAwait():

try
{
    result = App.AcquireTokenForClient(_resourceIds).ExecuteAsync().Result;
}

当我这样做时,调试器实际上捕获了一个异常,而不是突然关闭。对于我的情况,事实证明我的范围(在您的代码中也称为 _resourceIds)是错误的。实际适用于我的用例的范围:

private string[] Scopes = new[]
{
    "https://graph.microsoft.com/.default"
};

问题是我没有捕捉到一般异常。以下内容让我发现了我的问题,即我没有正确的范围:

public async Task<AuthenticationResult> GetMyAccessTokenResultAsync()
{
    AuthenticationResult result = null;

    try
    {
        result = await App.AcquireTokenForClient(_resourceIds).ExecuteAsync();
    }
    catch(MsalClientException ex)
    {
        ...
    }
    catch(Exception ex)
    {
        ...
    }

    return result;            
}