PowerShell 7.3 - how to to Invoke Web Request with OAuth 2.0 Bearer Token for REST API
I need some guidance on I'm trying to invoke a REST API using PowerShell 7.3 that requires OAuth 2.0 for authentication. I've successfully obtained the bearer token through a previous step, but when I attempt to make a web request using `Invoke-RestMethod`, I'm running into a `403 Forbidden` behavior. Here’s the code snippet I'm using: ```powershell # Get OAuth 2.0 Bearer Token $clientId = "your_client_id" $clientSecret = "your_client_secret" $tokenUrl = "https://api.example.com/token" $body = @{ grant_type = "client_credentials"; client_id = $clientId; client_secret = $clientSecret } $tokenResponse = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body $body -ContentType "application/x-www-form-urlencoded" $bearerToken = $tokenResponse.access_token # Make API Request $apiUrl = "https://api.example.com/resource" $headers = @{ Authorization = "Bearer $bearerToken" } $response = Invoke-RestMethod -Uri $apiUrl -Method Get -Headers $headers ``` Despite setting the authorization header correctly, the response I'm getting is: ``` Invoke-RestMethod : The remote server returned an behavior: (403) Forbidden. ``` I’ve verified that the token is valid and has the necessary permissions by testing it with Postman. I suspect it might be an scenario with how I'm formatting the HTTP request or perhaps there's a missing header that needs to be included. I've also tried adding `-SkipCertificateCheck` in case there’s an SSL scenario, but that didn’t resolve the question. Any ideas on what could be going wrong or how to troubleshoot this further? I'm working in a Ubuntu 20.04 environment. Is there a better approach?