'Ansible Tower API calls work from Postman but not in Powershell

I'm using a personal access token to make a call to /api/v2/hosts. In the header, I have "Authorization: bearer <personal access token". In postman it works just fine, I get a list of the hosts. But in Powershell, using Invoke-RestMethod fails with

Invoke-RestMethod : {"detail":"Authentication credentials were not provided. To establish a login session, visit /api/login/."}

Does anyone have any idea why this would be the case?

Here's the code: all values are non-sensitive. They are throwaway:

Here's the relevant code, non of the information is sensitive, it's non-production throwaway:

$headers = @{ Accept = "application/json"; Authorization = "bearer YqQoPFTD7GRZqB3XxAvVlZ2SUWxZGc"; "Accept-Encoding" = "gzip, deflate, br"}

$hosts=Invoke-RestMethod "https://10.100.235.4/api/v2/hosts" -Method Get -Headers $headers


Solution 1:[1]

The problem is that the response was a 301, and after the redirect the headers were being dropped. Apparently Powershell 7 has an option to stop this from happening, so I think that's the answer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Richard Wolford