从发布定义触发 TFS 构建时出现未经授权的错误

Getting Unauthorised error while triggering TFS build from release definition

我需要在成功部署发布后触发构建。我尝试在发布定义中的 Powershell 中使用以下代码。

执行后,出现此错误 - 由于凭据无效,访问被拒绝

$url = "http://abc:8080/tfs/GlobalCollection/Project/_apis/build/builds?
 api-version=2.0"

$body = "{ 'definition' : { 'id' : 1} }"

$type = "application/json"

$headers = @{
Authorization = "Basic d3JlblxzcsampleTIzNA=="
}

Write-Host "URL: $url"

$definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -
Method Post -Headers $headers

Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)"`

根据我的测试,你可以使用 -UseDefaultCredentials :

$type = "application/json"

$url = "http://abc:8080/tfs/GlobalCollection/Project/_apis/build/builds?api-version=2.0"

$body = "{ 'definition' : { 'id' : 56} }"

Write-Host "URL: $url"

$definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -Method Post -UseDefaultCredentials

Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)"

或者提供特定的凭据:

$user = "username"
$password = "password"

# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))
$headers = @{Authorization=("Basic {0}" -f $base64AuthInfo)}
$type = "application/json"

$url = "http://abc:8080/tfs/GlobalCollection/Project/_apis/build/builds?api-version=2.0"

$body = "{ 'definition' : { 'id' : 56} }"

Write-Host "URL: $url"

$definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -Method Post -Headers $headers

Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)"