I'm trying to use the Azure Management API to get metrics data. However it is throwing a 403 exception. Does anyone have any idea why this code wouldn't work? I feel this code is pretty simple and is based on the MSDN article but still throws a 403. Any help is greatly appreciated!
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;
}
Please have a try to create the service principal and assign the corresponding role to the service principal. We can create it easily using PowerShell. More Info about how to get access token please refer to the article .
New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId
New-AzureRmRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $app.ApplicationId.Guid
As I have no metricdefinitions info in the resource, when I try to get metric info then I get 404 error. While I try another API /providers/microsoft.insights/alertrules?api-version=2016-03-01
. It works correctly for me.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.