Home > Enterprise >  Invoke-RestMethod : The remote server returned an error: (403) Forbidden PowerShell
Invoke-RestMethod : The remote server returned an error: (403) Forbidden PowerShell

Time:07-01

I want to get the display name and createdDateTime of Azure AD Groups by calling MS Graph from PowerShell.

For that, I'm using below PS Script:

$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

It failed with 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

I have given permissions for Group.Read.All and Directory.Read.All.

CodePudding user response:

Please check what type of permissions you granted for Group.Read.All and Directory.Read.All.

  • If you are trying to access the API as signed-in user, then you have to use Delegated permissions.
  • If you are trying to access the API without signed-in user, then you have to use Application permissions.

I executed the same script in my environment and got the same error when I have Delegated permissions without signed-in user like below:

enter image description here

To resolve the error, I granted Application permissions for Group.Read.All and Directory.Read.All and executed the below script:

$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

And I got the results successfully like below:

![enter image description here](https://i.imgur.com/YoTlhlt.png)

  • Related