我正在创建一个 PowerShell 脚本来从 Azure 获取指标。我有一个应用程序注册,具有 Insights-UserMetric.Read.All(应用程序类型)的 API 权限。此外,在订阅级别还为此应用程序分配了监控读者角色。运行脚本时,我收到错误:
{ "error": { "code": "AuthenticationFailed", "message": "Authentication failed." } }
我尝试将角色提升为贡献者,只是为了检查我是否没有足够的权限,但即使拥有贡献者角色,我仍然收到同样的错误
脚本如下:
$ClientId = 'someClientId'
$ClientSecret = 'someClientSecret'
$Tenantid = 'someTenantId'
$TokenBody = @{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
Client_Id = $ClientId
Client_Secret = $ClientSecret
}
$TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$Tenantid/oauth2/v2.0/token" -Method POST -Body $TokenBody
$Headers = @{
"Authorization" = "Bearer $($tokenResponse.access_token)"
"Content-type" = "application/json"
}
$Uri = 'https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.EventHub/namespaces/$eventHub/providers/Microsoft.Insights/metrics?api-version=2018-01-01'
Invoke-RestMethod -Headers $Headers -Uri $Uri -Method GET
感谢任何形式的指导
答案1
问题已解决。Token 部分已修复:
$TokenBody = @{
Grant_Type = "client_credentials"
Scope = "https://management.azure.com/.default"
Client_Id = $ClientId
Client_Secret = $ClientSecret
Tenant_Id = $TenantId
}