我尝试使用Azure Management API获取指标数据。然而它抛出403异常。有谁知道为什么这段代码不起作用?我觉得这段代码非常简单,并且基于MSDN文章,但仍然会抛出403.非常感谢任何帮助!
private string GetAccessToken()
{
var authenticationContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", TenantID));
var credential = new ClientCredential(clientId: AppID, clientSecret: SecretKey);
var result = authenticationContext.AcquireToken(resource: "https://management.core.windows.net/",
clientCredential: credential);
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
...
using (var client = new HttpClient())
{
string header = GetAccessToken();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", header
);
if (! resourceID.StartsWith("/"))
{
resourceID = "/" + resourceID;
}
string url = "https://management.azure.com" + resourceID +
"/providers/microsoft.insights/metricdefinitions?api-version=2016-03-01";
var response = client.GetStringAsync(url).Result;
return response;
}
答案 0 :(得分:0)
请尝试创建服务主体并将相应的角色分配给服务主体。我们可以使用PowerShell轻松创建它。有关如何获取访问令牌的更多信息,请参阅article。
New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId
New-AzureRmRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $app.ApplicationId.Guid
由于我在资源中没有metricdefinitions信息,当我尝试获取度量信息时,我得到404错误。我尝试了另一种API /providers/microsoft.insights/alertrules?api-version=2016-03-01
。它适用于我。