使用C#及Microsoft.Azure.Management.Fluent操作Azure遇授权异常
Hey there, let's break down what's happening and get your VM listing code working.
First, let's cut to the chase: that error is a RBAC (Role-Based Access Control) permission issue. The service principal (the identity your code is using via that auth file) doesn't have the right permissions to read virtual machine data in your subscription. The fact that the client ID and object ID look identical in the error message is just a quirk of how Azure surfaces service principal info in some cases—don't get hung up on that, it's not the root problem.
Why this worked for Blob/File storage but not VMs
Your earlier work with WindowsAzure.Storage used storage-specific authentication (like access keys or SAS tokens) which are separate from Azure's management API RBAC permissions. The VM listing code uses the Azure Resource Manager (ARM) API, which enforces strict RBAC rules that don't apply to storage account operations.
Step-by-step fixes
Assign the correct RBAC role to your service principal
You need to grant your service principal a role that includes theMicrosoft.Compute/virtualMachines/readaction. The easiest, most appropriate options are:- Reader: Gives read-only access to all resources in the subscription (perfect for your VM listing use case)
- Virtual Machine Contributor: Gives full access to VMs (if you plan to modify them later)
To do this in the Azure Portal:
- Navigate to your target Subscription
- Go to Access control (IAM)
- Click Add > Add role assignment
- Search for and select the role you want (Reader or Virtual Machine Contributor)
- Under Members, select User, group, or service principal and search for your service principal's client ID or name
- Save the assignment
Or via Azure CLI (faster if you prefer command line):
az role assignment create --assignee YOUR_CLIENT_ID --role "Reader" --subscription YOUR_SUBSCRIPTION_IDWait for permission propagation
Azure can take 1-5 minutes to roll out RBAC changes, so don't panic if your code still fails immediately after assigning the role—give it a minute to take effect.Confirm you're targeting the right subscription
Double-check that the subscription in your auth file matches the one you assigned the role to. If you want to be explicit in code (to avoid default subscription confusion), replace.WithDefaultSubscription()with:.WithSubscription("YOUR_SUBSCRIPTION_ID")
Quick debug check
To confirm your code is using the correct subscription context, add this line before listing VMs:
Console.WriteLine($"Active subscription: {azure.SubscriptionId}");
内容的提问来源于stack exchange,提问作者Valentin Fritz aka. VFRZ

