背景
我正在调用 Microsoft 的 Azure 消费端点的 restful API,如下所述。
https://learn.microsoft.com/en-gb/rest/api/consumption/reservationrecommendations/list
然而,我总是遇到以下错误。身份验证令牌没有注册级别访问权限。
{
"error": {
"code": "401",
"message": "Authentication token doesn't have enrollment level access.
}
}
令牌有效,可用于访问消费 API 下的其他端点。Azure 页面上的“试一试”测试链接实际上返回 200,但是当我发出调用时,却得到了 401。
问题
是否有人能够解释这个错误信息?我在任何地方都找不到关于这个错误的帮助。
代码
身份验证
private static string GetAccessToken(string clientId, string clientSecret, string tenantId)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json;");
string hostname = $"https://login.microsoftonline.com/{tenantId}/oauth2/token";
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("resource", "https://management.azure.com/")
});
HttpResponseMessage httpResponse = client.PostAsync(hostname, content).Result;
var responseString = httpResponse.Content.ReadAsStringAsync();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
dynamic tokenObject = JsonConvert.DeserializeObject(responseString.Result);
return tokenObject.access_token;
}
else
{
return null;
}
}
API调用
public static dynamic GetReservationRecommendations(Params parameters)
{
var token = GetAccessToken(parameters.ClientId, parameters.ClientSecret, parameters.TenantId);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json;");
string hostname = $"https://management.azure.com/subscriptions/{parameters.SubscriptionId}/providers/Microsoft.Consumption/reservationRecommendations?api-version=2018-10-01";
HttpResponseMessage httpResponse = client.GetAsync(hostname).Result;
var responseString = httpResponse.Content.ReadAsStringAsync();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
return responseString.Result;
}
else
{
return null;
}
}