簡體   English   中英

Invoke-RestMethod:遠程服務器返回錯誤:(403) Forbidden PowerShell

[英]Invoke-RestMethod : The remote server returned an error: (403) Forbidden PowerShell

我想通過從 PowerShell 調用 MS Graph 來獲取 Azure AD 組的display namecreatedDateTime

為此,我使用以下 PS 腳本:

$Body = @{
    client_id = "app_id"
    client_secret = "secret"
    scope = "https://graph.microsoft.com/.default"
    grant_type = 'client_credentials'
}

$Connect_Graph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/my_tenant_id/oauth2/v2.0/token" -Method Post -Body $Body

$token = $Connect_Graph.access_token

$query = "https://graph.microsoft.com/v1.0/groups/"
$groups = (Invoke-RestMethod -Headers @{Authorization = "Bearer $($token)"} -Uri $query -Method Get).value | Select displayName, createdDateTime

它以403 Forbidden失敗

Invoke-RestMethod : The remote server returned an error: (403) Forbidden.
At C:\Users\script.ps1:13 char:12
+ $groups = (Invoke-RestMethod -Headers @{Authorization = "Bearer $($to ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

我已授予Group.Read.AllDirectory.Read.All的權限。

請檢查您授予Group.Read.AllDirectory.Read.All的權限類型。

  • 如果您嘗試以登錄用戶身份訪問 API,則必須使用委派權限。
  • 如果您嘗試在沒有登錄用戶的情況下訪問 API,則必須使用應用程序權限。

我在我的環境中執行了相同的腳本,當我在沒有登錄用戶的情況下獲得了委派權限時,得到了相同的錯誤,如下所示:

在此處輸入圖像描述

為了解決這個錯誤,我授予了Group.Read.AllDirectory.Read.All應用程序權限並執行了以下腳本:

$Body = @{
    client_id = "app_id"
    client_secret = "secret"
    scope = "https://graph.microsoft.com/.default"
    grant_type = 'client_credentials'
}
$Connect_Graph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/my_tenant_id/oauth2/v2.0/token" -Method Post -Body $Body
$token = $Connect_Graph.access_token
$query = "https://graph.microsoft.com/v1.0/groups/"
(Invoke-RestMethod -Headers @{Authorization = "Bearer $($token)"} -Uri $query -Method Get).value | Select displayName, createdDateTime

我成功地得到了如下結果:

![在此處輸入圖片描述](https://i.imgur.com/YoTlhlt.png)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM