在构建任务中使用$(System.AccessToken)运行Invoke-RestMethod错误



当尝试使用$(System.AccessToken)的值作为凭据访问REST API时,我得到了401(大概)。我正在运行的管道与我正在使用的API URL在相同的ADS 2020 on-prem服务器上。

构建日志中的错误信息如下所示:

TF400813: Resource not available for anonymous access.日志含义需要客户端身份验证。- Azure DevOps Server

受此技术的启发,下面是我的PowerShell内联脚本任务中的代码:
$Params = @{
ContentType = 'application/json'
Headers = @{ Authorization = 'Bearer $(System.AccessToken)' }
Method = 'Get'
Uri = 'http://host/collection/project/_apis/build/builds/' + $(Build.BuildId) + '?api-version=6.0'
}
$Result = Invoke-RestMethod @Params

我也试过这个,借用了这个答案:

$Params = @{
ContentType = 'application/json'
Method = 'Get'
Uri = 'http://$(System.AccessToken)@host/collection/project/_apis/build/builds/' + $(Build.BuildId) + '?api-version=6.0'
}
$Result = Invoke-RestMethod @Params

我已经小心地打开了Allow scripts to access the OAuth token选项,如下所示。

的奇怪之处在于它第一次通过(上面的第一个代码块)就工作了。现在,无论我怎么尝试,我总是得到上面的错误。

我如何在构建任务中使用$(System.AccessToken)的值来访问同一服务器上的REST API ?

——编辑——

我也试过另一种变量语法:

$BuildId = $env:BUILD_BUILDID
$Token = $env:SYSTEM_ACCESSTOKEN
$Params = @{
ContentType = 'application/json'
Headers = @{ Authorization = 'Bearer $Token' }
Method = 'Get'
Uri = 'http://host/collection/project/_apis/build/builds/' + $BuildId + '?api-version=6.0'
}
$Result = Invoke-RestMethod @Params

苦苦思索后,我终于找到了合适的组合:

$BuildId = $env:BUILD_BUILDID
$Token = $env:SYSTEM_ACCESSTOKEN
$Params = @{
ContentType = "application/json"
Method = "Get"
Uri = "http://host/collection/project/_apis/build/builds/$BuildId"
}
$Result = Invoke-RestMethod @Params -Headers @{ Authorization = "Bearer $Token" }

我一时兴起试了试。我不知道为什么这个通过了,而其他的没有,但没关系。它运行。我在里面插了一面旗帜。

相关内容

最新更新