首页 > 解决方案 > 通过 Powershell 连接到 TFS 的身份验证错误

问题描述

我对 Rest API 调用知之甚少,所以请耐心等待。我正在尝试通过 Powershell 使用 Rest API 对 TFS 2017 构建进行排队。我尝试使用 TFS API,但发现它无法为我工作。这就是我所拥有的:

$Uri = "http://MyTFS:8080/tfs/DefaultCollection/Project/_apis/build/builds?api-version=3.0"
$TFSAPIKeyForAutomatedBuild = SecretKey
$body = @"
   {
    "definition": 
        {
         "ID": "BuildID"
        },
    "RequestedFor":
        {
        "Id":"MyID"
        }
    }
"@
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer $TFSAPIKeyForAutomatedBuild")
$buildresponse = Invoke-RestMethod -Method Post -header $headers -ContentType application/json -Uri $Uri -Body (ConvertTo-Json $Body)

但是,当我运行它时,我得到了错误:

TF400813: 资源不可用于匿名访问。需要客户端身份验证

顺便说一句,我已经能够使用 Postman 对构建进行排队,因此它应该以一种或另一种方式工作。

任何建议,将不胜感激。

标签: restpowershellrestful-authentication

解决方案


这就是解决我的问题的原因。您必须像这样对用于连接到 TFS 的令牌进行编码:

$encodedPAT = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$TFSAPIKeyForAutomatedBuild"))
$Uri = "http://MyTfs:8080/tfs/DefaultCollection/Projects/_apis/build/builds?api-version=3.0"

$body = @{ definition = @{id = BuildID} }
$bodyJson = ConvertTo-Json $body

write-host $bodyJson
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Basic $encodedPAT")

$buildresponse = Invoke-RestMethod -Method Post -header $headers -ContentType application/json -Uri $Uri -Body (ConvertTo-Json $body)

我还更改了 json 的格式,因为它引发了关于反序列化的错误。


推荐阅读