尝试使用ARM API获取令牌时未经授权 [英] Unauthorized when try to get token using ARM API

查看:97
本文介绍了尝试使用ARM API获取令牌时未经授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用 Azure资源管理器 API获取令牌,但得到 401-Unauthorized 作为响应.我的代码如下:

I am trying to get token from using Azure Resource Manager API but getting 401-Unauthorized in response.I have my code as below :

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);

推荐答案

我不完全理解您的代码,但是我知道如何构造ARM API调用,因此我可以帮助您了解核心事实. 让我惊讶的是您的POST URL看起来不正确:

I dont fully understand your code but i know how to construct ARM API calls so i can help you out with the core facts. What jumps out at me is the fact that your POST URL looks wrong:

  1. 您应该使用 https://login.microsoftonline.com/-签出以下博客文章简化我们的Azure AD身份验证流

  1. you should be using https://login.microsoftonline.com/ - check out the following blogpost Simplifying our Azure AD Authentication Flows

在您的POST uri中需要有tenantID,而不是subscriptionID.通过将RBAC角色分配给为AzureAD应用创建的私密主体来管理对订阅的访问

There needs to be the tenantID in your POST uri, not the subscriptionID. Access to subscriptions is managed through assigning RBAC Roles to the serivceprincipal created for the AzureAD App

这里是一个示例调用.我使用邮递员检查我构造的呼叫是否使用正确的值和参数:

Here is an example call. I use Postman to check if my constructed calls use the correct values and parameters:

请求

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]"
}

这篇关于尝试使用ARM API获取令牌时未经授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆