尝试使用ARM API获取令牌时未经授权

时间:2017-01-19 07:31:24

标签: azure azure-resource-manager

我正在尝试使用 Azure资源管理器 API获取令牌,但在响应中获取 401-Unauthorized 。我的代码如下所示:

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
   "Basic",
   Convert.ToBase64String(
       System.Text.ASCIIEncoding.ASCII.GetBytes(
           string.Format("{0}:{1}", client_Id, client_secret))));

var content = new FormUrlEncodedContent(new KeyValuePair<string, string>[]{

            new KeyValuePair<string, string>("grant_type", "client_credentials")
        });

content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

var response = client.PostAsync("https://login.windows.net/subscriptionId/oauth2/token", content);

2 个答案:

答案 0 :(得分:0)

根据您的代码,您可以参考以下代码来检索您的令牌:

var client = new HttpClient();

var content = new FormUrlEncodedContent(new KeyValuePair<string, string>[]{
    new KeyValuePair<string, string>("resource", "https://management.core.windows.net/"),
    new KeyValuePair<string, string>("grant_type", "client_credentials"),
    new KeyValuePair<string, string>("client_id", "{ClientID}"),
    new KeyValuePair<string, string>("client_secret", "{ClientSecret}")
});

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsync("https://login.windows.net/{TennantID}/oauth2/token", content);

Console.WriteLine(await response.Content.ReadAsStringAsync());

结果:

enter image description here

有关更多详细信息,请参阅此blog有关使用Azure ARM REST API - 获取访问令牌的信息。

答案 1 :(得分:0)

我不完全理解你的代码,但我知道如何构建ARM API调用,所以我可以帮助你解决核心事实。 我突然发现你的POST URL看起来错了:

  1. 您应该使用https://login.microsoftonline.com/ - 请查看以下博文Simplifying our Azure AD Authentication Flows

  2. 您的POST uri中需要有tenantID,而不是subscriptionID。通过将RBAC角色分配给为AzureAD应用程序创建的serivceprincipal来管理对订阅的访问

  3. 这是一个示例调用。我使用Postman来检查我构造的调用是否使用了正确的值和参数:

    请求

    POST /[YOURTENANTID]/oauth2/token?api-version=1.0 HTTP/1.1
    Host: login.microsoftonline.com
    Cache-Control: no-cache
    Connection: Keep-Alive
    Content-Type: application/x-www-form-urlencoded
    Expect: 100-continue
    Postman-Token: [token]
    
    grant_type=client_credentials&client_id=[YOURCLIENTID]&client_secret=[YOUR-URLENCODED-Secret]&resource=https://management.azure.com/
    

    响应:

    {
     "token_type": "Bearer",
     "expires_in": "3599",
     "ext_expires_in": "0",
     "expires_on": "1485695000",
     "not_before": "1485691100",
     "resource": "https://management.azure.com/",
     "access_token": "[TOKEN]"
    }