1

I'm trying to access a web api for Sonarqube on our local server. The examples in the Sonarqube documentation are all curl-based and I'm trying to translate them to PowerShell, either Invoke-WebRequest or Invoke-RestMethod. I'm having issues with credentials. I keep getting a 401 Not Authorized error. I've reviewed every post I can find on doing this and I don't see a comprehensive complete answer on how to do this.

Here's what I'm running now:

$user='myUserid'
$password='myPassword'
$secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($user, $secpasswd)
$uri="http://myServer.ad1.prod:9000/api/properties"
Invoke-RestMethod -Uri $uri -Credential $cred -Method Get

And the response is:

Invoke-RestMethod : {"err_code":401,"err_msg":"Unauthorized"}

I've run the curl command as defined in the original product documentation and it works. Same userid, same password, same URI, same method.

Can anyone advise?

My curl command is:

curl -u myID:myPassword X GET http://myServer.ad.prod:9000/api/properties
Richard Schaefer
  • 525
  • 3
  • 13
  • 45

1 Answers1

5

I think you need to pass in a credential like this:

$username = "user"
$password = "password"
$authInfo = ("{0}:{1}" -f $username,$password)
$authInfo = [System.Text.Encoding]::UTF8.GetBytes($authInfo)
$authInfo = [System.Convert]::ToBase64String($authInfo)
$headers = @{Authorization=("Basic {0}" -f $authInfo)}

Invoke-RestMethod -Method Head -Uri "https://pathtowhatever" -ContentType 'text/json' -Headers $headers
Nick H.
  • 1,616
  • 14
  • 20