The remote server returned an error : (401) Unauthorized - PowerShell - Microsoft Graph API

The remote server returned an error : (401) Unauthorized - PowerShell - Microsoft Graph API

我正在尝试获取 resourceProvisioningOptions = Team 所在的所有组的列表,这里是 url,它通过 API 调用获取所有数据:

$clientID = xxxx
$tenantName = xxxx
$ClientSecret = xxxx
$resource = "https://graph.microsoft.com/"


$ReqTokenBody = @{
Grant_Type    = "client_credentials"
Scope         = "https://graph.microsoft.com/.default"
client_Id     = $clientID
Client_Secret = $clientSecret 
} 

$authheader = @{

    'Authorization' = "Bearer $($Tokenresponse.access_token)"
    'Content-Type'='application\json'

}

$TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody

$test = "'Team'"

$apiUrl = 'https://graph.microsoft.com/beta/groups?$filter=resourceProvisioningOptions/Any(x:x eq {0})' -f $test

$Data = Invoke-RestMethod -Uri $apiUrl -Headers $authheader -Body $ReqTokenBody -Method Get


$Groups = ($Data | select-object Value).Value | Select-Object  displayName, id, description, mail | Out-File .\texxtfile.txt

但是,当我尝试 运行 脚本时出现 401 错误,即使我拥有进行 API 调用所需的所有权限。

您可能在 AAD 应用程序中选择了应用程序权限。还有一个额外的步骤。您需要在应用程序注册门户中获得管理员同意您的应用程序才能使用 Group.Read.All 至 运行。如果您还没有在 UI 中执行此操作,这将失败。