
我正在建立一個 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
問題解決了。令牌部分已修復:
$TokenBody = @{
Grant_Type = "client_credentials"
Scope = "https://management.azure.com/.default"
Client_Id = $ClientId
Client_Secret = $ClientSecret
Tenant_Id = $TenantId
}