powershell - 需要将身份验证标头添加到 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 中启用某些设置?
解决方案
我通常参考这个演示在 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
在您的情况下,问题似乎是由编码引起的。尝试使用ASCII
or UTF8
,而不是Unicode
.
要查看更多详细信息,您可以查看“使用个人访问令牌”。
推荐阅读
- reactjs - React Native:更改中心屏幕中的按钮大小
- html - 如何将选择按钮与条款和条件文本对齐到同一行
- python - 内存分析,如何找到与对象关联的变量名
- python-3.x - 在虚拟 conda env(anaconda 3)中是否可以从基本 env 符号链接包?
- python-3.x - TypeError:预期的 str、bytes 或 os.PathLike 对象,而不是下载附件时出现 NoneType 错误
- azure - 如何让 Ubuntu 看到我在 azure 门户中增加了磁盘大小
- javascript - javascript localstorage 两个div
- django - 在 Django 中过滤嵌套的外键
- kubernetes - 如何在 Kubernetes 中跨所有节点均匀部署 pod?
- reactjs - 如何通过单击 React 中的链接打开表单?