如何使用C#客户端获取Azure令牌?

时间:2020-05-13 13:39:45

标签: c# azure rest asp.net-core postman

我正在尝试从我的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
    },
}

在登录后,Microsoft得到令牌,请求看起来像:

GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/North%20Europe/vmSizes?api-version=2019-12-01
Authorization: Bearer {{token.....}}

我需要获得令牌,以进行我不知道的请求, 我有以下凭据:

azure_client_id azure_client_secret azure_tenant_id azure_subscription_id

使用此凭据,如何获得此json结果,简而言之,如何获得令牌。

尝试的方法:

This one Read this but no info investigated also this one also this question in stackoveflow

P.S。我正在使用aspnet core 3.1 Web应用程序,也许它是Azure的更好客户端。我使用了ComputeClient,但没有成功。最后,我认为应该使用httpclient,但是首先我需要与邮递员进行测试。

1 个答案:

答案 0 :(得分:2)

如果要使用服务主体来管理Azure资源,我们需要将Azure RABC role分配给服务主体,例如Contributor。

例如

  1. 创建服务主体并为其分配Azure RABC角色。由于您要列出Azure VM的大小,因此我们可以使用虚拟机贡献者角色。
Vector

enter image description here

  1. 获取令牌
az login
az account set --subscription "<your subscription id>"

az ad sp create-for-rbac -n "readMetric" --role "Virtual Machine Contributor"
  1. 列出Azure VM大小
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

enter image description here

  1. 带有Azure Net SDK GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/eastus/vmSizes?api-version=2019-12-01 Authorization: Bearer {{token.....}} 的.Net Core
Microsoft.Azure.Management.Compute.Fluent

enter image description here