我正在尝试从我的 Azure 帐户获取所有虚拟机大小名称,并且我正在使用 This approach 在网站中,当我单击“尝试”时,我会得到我需要的结果。
Json 看起来像:
{
"value": [
{
"name": "Standard_D1_v2",
"numberOfCores": 1,
"osDiskSizeInMB": 1047552,
"resourceDiskSizeInMB": 51200,
"memoryInMB": 3584,
"maxDataDiskCount": 4
},
{
"name": "Standard_D2_v2",
"numberOfCores": 2,
"osDiskSizeInMB": 1047552,
"resourceDiskSizeInMB": 102400,
"memoryInMB": 7168,
"maxDataDiskCount": 8
},
}
登录后,微软获取 token 和请求如下所示:
GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/North%20Europe/vmSizes?api-version=2019-12-01
Authorization: Bearer {{token.....}}
我需要获取 token 来发出我不知道的请求, 我有如下凭据:
azure_client_id azure_client_secret azure_租户_id azure_subscription_id
使用此凭据如何获得此 json 结果,简而言之如何获取 token 。
尝试过的方法:
This one Read this but no info investigated also this one also this question in stackoveflow
附注我正在使用 aspnet core 3.1 Web 应用程序,也许它是更好的 azure 客户端。我使用ComputeClient但没有成功。最后我想使用httpclient,但首先我需要用postman进行测试。
最佳答案
如果您想使用服务主体来管理 Azure 资源,我们需要分配 Azure RABC role到服务主体,例如贡献者。
例如
- 创建服务主体并为其分配 Azure RABC 角色。由于您想要列出 Azure VM 大小,因此我们可以使用虚拟机贡献者角色。
az login
az account set --subscription "<your subscription id>"
az ad sp create-for-rbac -n "readMetric" --role "Virtual Machine Contributor"
- 获取 token
POST /<your AD tenant domain>/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type =client_credentials
&client_id=<>
&client_secret=<>
&scope=https://management.azure.com/.default
- 列出 Azure 虚拟机大小
GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/eastus/vmSizes?api-version=2019-12-01
Authorization: Bearer {{token.....}}
- .Net Core 与 Azure Net SDK
Microsoft.Azure.Management.Compute.Fluent
AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
clientId, // the sp appId
clientSecret, // the sp password
tenantId, // the sp tenant
AzureEnvironment.AzureGlobalCloud);
RestClient restClient = RestClient.Configure()
.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
.WithCredentials(credentials)
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Build();
ComputeManagementClient client = new ComputeManagementClient(restClient);
client.SubscriptionId = subscriptionId;// the subscription you use
var vmSizes= await client.VirtualMachineSizes.ListAsync("eastus");
foreach (var vmSize in vmSizes) {
Console.WriteLine("The VM Size Name : "+ vmSize.Name);
}
关于c# - 如何使用c#客户端获取azure token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61776190/