Azure错误:DefaultAzureCredential身份验证失败

时间:2020-07-07 22:28:46

标签: c# azure azure-sdk-.net azure-sdk

我正在研究Azure官方示例:Getting started - Managing Compute Resources using Azure .NET SDK。在应用尝试创建resourceGroup = await resourceGroups.CreateOrUpdateAsync(resourceGroupName, resourceGroup);的以下代码的行Resource Group上出现以下错误。我已按照示例提供的link进行了注册应用程序的说明。并且,assigned a role to app如下:

enter image description here

错误

Azure.Identity.AuthenticationFailedException HResult = 0x80131500 Message = DefaultAzureCredential身份验证失败。 来源= Azure.Identity

内部异常2: MsalServiceException:AADSTS70002:该客户端不存在或未为使用者启用。如果您是应用程序开发人员,请通过Azure门户中的“应用程序注册”配置新应用程序

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)中已注册应用的角色分配

enter image description here

身份验证和直接URI

enter image description here

已注册应用程序的API权限

enter image description here

UPDATE-2

@JoyWan一起工作,我能够解决此问题(感谢Joy)。以下是成功创建所有必需的compute resources(包括VM)的屏幕截图。 注意:点击图片可以更好地查看屏幕截图。

enter image description here

1 个答案:

答案 0 :(得分:1)

我测试了代码,它对我而言很好用。您提到的步骤也是正确的。

在此示例中,DefaultAzureCredential()实际上在本地使用了EnvironmentCredential(),因此,如果您在本地运行代码,请确保AD App {{1}中有Set Environment Variables }。

enter image description here

enter image description here

enter image description here

更新

在@nam的评论中,问题在于环境var昨天没有刷新,因为他昨天关闭了计算机并在今天重新启动了该机器,因此环境var处于同步状态,因此该应用程序开始运行。