How to fix: Invoke-RestMethod : The remote server returned an error: (403) Forbidden.

Phil Rawlings 0 Reputation points
2024-01-08T10:35:58.5466667+00:00
# Define the variables
$ClientID     = '****'
$ClientSecret = '****'
$TenantName   = '****'

# Create the access token based on the variables
$Body = @{
    Grant_Type    = "client_credentials"
    Scope         = "https://graph.microsoft.com/.default"
    Client_Id     = $ClientID
    Client_Secret = $ClientSecret
}

$Params = @{
    ContentType = "application/x-www-form-urlencoded"
    Body        = $Body
    Method      = "Post"
    URI         = "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token"
}

$Response = Invoke-RestMethod @Params

# Extract the access token from the response
$AccessToken = $Response.access_token

# Use the access token and the URI to get the list of application IDs
$Headers = @{
    Authorization = "Bearer $AccessToken"
}

$URI = "https://graph.microsoft.com/v1.0/applications"

$Result = Invoke-RestMethod -Uri $URI -Headers $Headers -Method Get

# Output the application IDs
$Result.value.id



I get a 403 on the $result line and I don't understand why.
Ultimately I want to write a script that pulls ALL information out from the application so we can store it as a backup as we purge unused applications, but I can't get passed the first stage of pulling in the applications' IDs

Any help or pointers will be much appreciated
Thanks

Microsoft Security | Microsoft Graph
{count} votes

1 answer

Sort by: Most helpful
  1. Phil Rawlings 0 Reputation points
    2024-01-08T10:59:41.18+00:00

    This is now fixed, I added application permissions rather than delegated ones and that solved the problem.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.