401 Unauthorized when interacting with Web API with Powershell


(Ryan Evans) #1

I am an admin on an organisation account and I have created a Token using the My Account>Security menu options.

I have then fed that Token into the below simple powershell script (I have removed the actual values used):

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;

$URL = “https://sonarcloud.io/api/authentication/login

$apiUser = “REDACTED”
$apiUserPassword = “REDACTED”

#Create our credentials object
$pwd = ConvertTo-SecureString $apiUserPassword -AsPlainText -Force;
$Cred = New-Object System.Management.Automation.PSCredential ($apiUser, $pwd);

$response = Invoke-WebRequest -Uri $URL -Credential $Cred -Method POST

The response I get is follows:

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

I have attempted this in Postman too using Http Basic Authentication and I get the same result.

Can any advise what I am doing wrong?

(Fabrice Bellingard) #2

Why are you trying to call /api/authentication/login? Can you try calling https://sonarcloud.io/api/users/current instead?

Also, when using a user token to authenticate with basic auth, its value must be passed as the login, with an empty password.

(Ryan Evans) #3

The documentation here is used for login - https://sonarcloud.io/web_api/api/authentication

However, I have put the token value in the username field and left the password blank and it works perfectly now thank you.