Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

powershell - need to add authentication header to azure devops api request

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 [domainusername]:[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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...