0
votes

I'm trying to get information on my latest builds by sending a GET request to the Azure DevOps REST Api. I'm using Azure DevOps Server 2020 with the Patch 1 update. I need to add an authorization header to the request. The header I added is not working.

I'm doing the request in Powershell. Here's my code:

$PAT = 'personal access token'
$ENCODED = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($PAT))

$headers = @{
Authorization="Basic $ENCODED"
}

Invoke-RestMethod -Uri [azure devops server url]/[project name]/_apis/build/latest/Build?api-version=5.0 -Method Get -Headers $headers

When I run the code I get the error: Invoke Method: The format of value [PAT] is invalid

UPDATE: I updated the header syntax. Now the reponse I get:

Invoke-RestMethod:

        TF400813: Resource not available for anonymous access. Client authentication required. - Azure DevOps Server

I also tried passing my Azure DevOps username and password in the header like this:

$headers = @{
  Authorization="Basic [domain\username]:[password]"
}

and I got this in response:

Invoke-RestMethod: Response status code does not indicate success: 401 (Unauthorized).

Do I have to enable some setting in Azure DevOps?

1
Try $headers = @{Authorization="Basic $ENCODED"} instead.AdminOfThings
I changed the header syntax. Now I get Invoke-RestMethod: TF400813: Resource not available for anonymous access. Client authentication required. - Azure DevOps Servermdailey77

1 Answers

1
votes

I usually reference to this demo to run REST API in PowerShell, it can work fine:

$uri = "request URI"

$pat = "personal access token"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $pat)))

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

$body = "{
           . . .
         }"

Invoke-RestMethod -Uri $uri -Headers $headers -Body $body -Method POST

In your case, the issue seems is caused by the encoding. Try using ASCII or UTF8, instead of Unicode.

To view more details, you can see "Use personal access tokens".