API Token ERROR 500 WITH Authorization’ = “Bearer $tokenString”}

Hi . I’m working with a REST API in PowerShell
I can successfully call the endpoint when I hard‑code the token into the header and it works fine.

But when I try to use the token dynamically from the first request (‘Authorization’ = “Bearer $tokenString”})

I always get: Invoke-RestMethod : The remote server returned an error: (500) Internal Server Error.
So: hard‑coding the token works, but using the variable $tokenString in the Authorization header results in 500.

The token value looks identical when printed to the console, same length, same ending.
Why would the API reject the request when the token comes from $response.Content, but accept it when the same token is written literally in the code? and how fix it.

$headers = @{‘accept’ =  '*/*'
             ‘clientId’      = ‘id’
             ‘clientSecret’  = ‘SOMESECRET’
             ‘tenantId’      = ‘SOMEid’}
$response = Invoke-WebRequest -Uri ‘https://TEST/api/Client/Token’ -Method ‘GET’ -Headers $headers
$tokenString = $response.Content
Write-Host $tokenString
$headersVac = @{‘accept’=  '*/*'
                ‘Authorization’ = “Bearer  $tokenString”}
$responseVac = Invoke-WebRequest -Uri ‘https://TEST/api/TEST/GetALLDATE?Id=2’ -Method ‘GET’  -Headers $headersVac
$data = $responseVac.Content
Write-Host $data

Hi, welcome to the forum :wave:

Have you validated that the token in the reponse and the hardcoded token are actually the same?

$hardToken = '<my token>'
$hardToken -eq $tokenString

That should return True if they really are identical.

Is this an API for a product or something private or internal? It would help if we could see the documentation. Otherwise we’re just guessing.

1 Like

Hi. I fixed the problem. I wrote the Authorization header as $tokenString without “Bearer”, and then the code started working.

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.