首页 > 解决方案 > 需要将身份验证标头添加到 azure devops api 请求

问题描述

我正在尝试通过向 Azure DevOps REST Api 发送 GET 请求来获取有关我最新版本的信息。我正在使用带有补丁 1 更新的 Azure DevOps Server 2020。我需要在请求中添加授权标头。我添加的标题不起作用。

我正在 Powershell 中执行请求。这是我的代码:

$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

当我运行代码时,我收到错误:Invoke Method: The format of value [PAT] is invalid

更新:我更新了标题语法。现在我得到的回复:

Invoke-RestMethod:

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

我还尝试在标题中传递我的 Azure DevOps 用户名和密码,如下所示:

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

我得到了这个回应:

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

我是否必须在 Azure DevOps 中启用某些设置?

标签: powershellazure-devopsazure-devops-rest-api

解决方案


我通常参考这个演示在 PowerShell 中运行 REST API,它可以正常工作:

$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

在您的情况下,问题似乎是由编码引起的。尝试使用ASCIIor UTF8,而不是Unicode.

要查看更多详细信息,您可以查看“使用个人访问令牌”。


推荐阅读