3

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?

2
  • 1
    Try $headers = @{Authorization="Basic $ENCODED"} instead. Commented Jan 6, 2021 at 16:02
  • I changed the header syntax. Now I get Invoke-RestMethod: TF400813: Resource not available for anonymous access. Client authentication required. - Azure DevOps Server Commented Jan 6, 2021 at 17:37

1 Answer 1

4

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".

Sign up to request clarification or add additional context in comments.

1 Comment

It was a token encoding issue. Your solution worked. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.