Back
Featured image of post Invoke-WebRequest and Invoke-RestMethod get Unauthorized without any reason

Invoke-WebRequest and Invoke-RestMethod get Unauthorized without any reason

In my case, this was only the case when I used Windows PowerShell (e.g., PowerShell 5.x)! PowerShell Core (7.x) worked fine.

I use PowerShell to access a lot of API’s! Since a while some calls that are correct get the error: “The remote server returned an error: (401) Unauthorized.”.

I took me a while and a lot of Fiddler sessions to find a header in some of the requests: “Expect: 100-continue”! I found this only in calls from Windows PowerShell (e.g., PowerShell 5.x). In general, this header is a good thing! But some API providers have issues with it.

That both Invoke-WebRequest and Invoke-RestMethod have the same behaviour make sense, both use System.Net.HttpWebRequest, which uses the namespace System.Net.Http.Headers.

Here is the error that I got from several API providers:

Exception : The remote server returned an error: (401) Unauthorized.
Reason    : WebException
Target    : System.Net.HttpWebRequest

Based on the docs that I found, the default value is true! Why ever I saw this Header in Windows PowerShell only! PowerShell Core (on any Plattform) never added this header. It is enabled by default on both.

Anyway, you can disable this header:

ServicePointManager.Expect100Continue = false;

In my case, I just added the following to my scripts and modules:

if ([Net.ServicePointManager]::Expect100Continue -ne $false)
{
   [Net.ServicePointManager]::Expect100Continue = $false
}

You can check if Expect100Continue is enabled (this the default):

[Net.ServicePointManager]::Expect100Continue