401 Unauthorized when interacting with Web API with Powershell

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?

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.

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.

i wrote an inline powershell script referred by this site https://writeabout.net/2018/09/25/fail-your-azure-devops-pipeline-if-sonarqube-quality-gate-fails/ to generate a build stop when a quality gate fails, but i keep getting 401 unauthorized message, im new to powershell does someone have an idea on this?

Hello crispin, is this problem resolved, if so, could you please help me with the fix .