CodexBloom - Programming Q&A Platform

PowerShell 7.3 scenarios to invoke REST API with OAuth token due to 'invalid_grant' scenarios

👀 Views: 24 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-03
PowerShell API OAuth

I'm sure I'm missing something obvious here, but I tried several approaches but none seem to work... I'm trying to invoke a REST API using PowerShell 7.3 that requires OAuth 2.0 authentication. I've generated the access token correctly, but when I attempt to make a request to the API endpoint, I receive an 'invalid_grant' behavior. Here's the relevant portion of my code where I retrieve the token and make the request: ```powershell # Define the OAuth token endpoint and client credentials $tokenUrl = "https://api.example.com/oauth/token" $clientId = "your_client_id" $clientSecret = "your_client_secret" # Create the request body for token retrieval $body = @{ grant_type = "client_credentials" client_id = $clientId client_secret = $clientSecret } | ConvertTo-Json # Get the access token $response = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body $body -ContentType "application/json" $accessToken = $response.access_token # Now use the access token to call the API $apiUrl = "https://api.example.com/data" $headers = @{ "Authorization" = "Bearer $accessToken" } $result = Invoke-RestMethod -Uri $apiUrl -Method Get -Headers $headers ``` When I run this, I receive the following behavior message: "behavior": "invalid_grant", "error_description": "Invalid client credentials". I've confirmed that the client ID and secret are correct and haven't expired. I've also tried specifying different grant types like `authorization_code`, but that results in a different behavior. I've made sure that my PowerShell script has access to the internet and can reach the token endpoint. What could be causing the 'invalid_grant' behavior in this context? Is there something I might be missing in the token request or in the API call? Any help would be greatly appreciated! My development environment is Linux. Has anyone else encountered this?