Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.

JuddSteven
Kilo Contributor

Hi Community,

I'm trying to utilize REST API to do some automations.

My code is working well on my developer instance:

# Eg. User name="admin", Password="admin" for this code sample.
$user = "admin"
$pass = "admin"

# Build auth header
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass)))

# Set proper headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))
$headers.Add('Accept','application/json')


# Specify endpoint uri
$uri = "https://downeritadtl.service-now.com/api/now/table/incident?sysparm_query=number%3DINC0222772&sysparm_limit=1"

# Specify HTTP method
$method = "get"

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"

# Send HTTP request
$response = Invoke-RestMethod -Headers $headers -Method $method -Uri $uri

# Print response
$response.Result

I tried it on a client instance without  admin role and its working fine as well.

However I get the following issue on another instance:

Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.
At line:23 char:13
+ $response = Invoke-RestMethod -Headers $headers -Method $method -Uri ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

The user that is using the instance that is getting the error already has an admin role.

What could be causing the 401?

3 REPLIES 3

Giles Lewis
Giga Guru

401 for GET almost always means bad username or bad password.

If you are blocked by an ACL the status will 200 with no data.

suglosta
Kilo Contributor

Hi,

I am not expecting you still have this issue but just to prevent other people from wasting the time.

If your password is strong enough and contain some chars like $ you must use single quotes.

$user = 'admin'
$pass = 'admin'

Kalpana11
Kilo Explorer

I am also getting same error 

 

Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.

 

Please help here