未处理的异常:Microsoft.Rest.Azure.CloudException

Unhandled Exception: Microsoft.Rest.Azure.CloudException

我收到这个错误:

Unhandled Exception: Microsoft.Rest.Azure.CloudException: The client 'XXX' with object id 'XXX' does not have authorization to perform action 'Microsoft.Resources/subscriptions/resourcegroups/write' over scope '/subscriptions/YYY/resourcegroups/FluentRG' or the scope is invalid. If access was recently granted, please refresh your credentials.

我已经将我的 Azure 帐户登录到 VS Code,并且我已将我的电子邮件地址作为当前订阅的贡献者授予权限。尽管如此,还是看到了这个异常。

    using System;
    using Microsoft.Azure.Management.Compute.Fluent;
    using Microsoft.Azure.Management.Compute.Fluent.Models;
    using Microsoft.Azure.Management.Fluent;

    namespace RESTApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                var azure = Azure.Authenticate("Azure-authentication.txt").WithDefaultSubscription();
                Console.WriteLine("Creating a new VM...");

                var windowsVM = azure.VirtualMachines.Define("VMCreatedWithFluent")
                    .WithRegion("West Europe")
                    .WithNewResourceGroup("FluentRG")
                    .WithNewPrimaryNetwork("10.0.0.0/28")
                    .WithPrimaryPrivateIPAddressDynamic()
                    .WithNewPrimaryPublicIPAddress("fluentdns")
              .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012Datacenter)
                    .WithAdminUsername("serverAdmin")
                    .WithAdminPassword("mySuperSecurePassword18")
                    .WithSize(VirtualMachineSizeTypes.StandardDS3V2)
                    .Create();

                Console.WriteLine("Successfully created a new VM: {0}!", windowsVM.Id);
                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
    }
}

}

我找到了你想引用的blog(因为代码和你的一样,也使用Azure-authentication.txt来授权)。

在此博客中,它使用 Azure-authentication.txt 中的服务主体凭据进行身份验证,而不是您登录的用户帐户,要解决此问题,您需要为您的服务主体分配一个 RBAC 角色,只需按照blog.

中的步骤 Setting up a Service Principal

您也可以在门户中执行此操作,如果您完全遵循此博客,服务主体名为 FluentAPIApp,只需导航至门户中的订阅 -> Access control (IAM) -> 搜索为其名称分配一个 Contributor,如下所示。