Azure error: DefaultAzureCredential authentication failed

Azure error: DefaultAzureCredential authentication failed

我正在处理官方 Azure 示例:Getting started - Managing Compute Resources using Azure .NET SDK. And getting the following error on line resourceGroup = await resourceGroups.CreateOrUpdateAsync(resourceGroupName, resourceGroup); of the following code where app is trying to create a Resource Group. I have followed the instructions for Registering an app and from this link provided by the sample. And, have assigned a role to app 如下:

错误:

Azure.Identity.AuthenticationFailedException HResult=0x80131500 Message=DefaultAzureCredential authentication failed. Source=Azure.Identity

Inner Exception 2: MsalServiceException: AADSTS70002: The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal

static async Task Main(string[] args)
{
    var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
    var resourceClient = new ResourcesManagementClient(subscriptionId, new DefaultAzureCredential());

    // Create Resource Group
    Console.WriteLine("--------Start create group--------");
    var resourceGroups = resourceClient.ResourceGroups;
    var location = "westus2";
    var resourceGroupName = "QuickStartRG";
    var resourceGroup = new ResourceGroup(location);
    resourceGroup = await resourceGroups.CreateOrUpdateAsync(resourceGroupName, resourceGroup);
    Console.WriteLine("--------Finish create group--------");

    // Create a Virtual Machine
    await Program.CreateVmAsync(subscriptionId, "QuickStartRG", location, "quickstartvm");

    // Delete resource group if necessary
    //Console.WriteLine("--------Start delete group--------");
    //await (await resourceGroups.StartDeleteAsync(resourceGroupName)).WaitForCompletionAsync();
    //Console.WriteLine("--------Finish delete group--------");
    //Console.ReadKey();
}

更新:

根据示例中的说明,以下是我 Used the portal to create an Azure AD application and service principal that can access resources 的方法。我可能没有在这里做某事。请让我知道我在这里没有做什么:

访问控制 (IAM) 中已注册应用的角色分配:

身份验证和直接 URI:

API 已注册应用的权限:

UPDATE-2:

@JoyWan 合作,我解决了这个问题(谢谢 Joy)。下面是成功创建所有必需 compute resources 包括 VM 的屏幕截图。 注意:单击图像可以更好地查看屏幕截图。

我测试了代码,它在我这边运行良好。你说的步骤也是正确的。

在此示例中,DefaultAzureCredential() actually uses the EnvironmentCredential() in local, so if you run the code in local, make sure you have Set Environment Variables 与 AD 应用 Client ID, Client Secret, Tenant ID

更新:

根据@nam 的评论,问题是昨天没有刷新环境变量,因为他昨天关闭了机器,今天又重新启动了机器,环境变量同步了,因此应用程序开始工作了。