TeamCity REST Api returns 403 使用系统凭据

TeamCity REST Api returns 403 using system credentials

当我 运行 在 TeamCity 上构建时,我想用环境变量标记构建。我希望这可能是直截了当的,但似乎没有内置的方法可以做到这一点。我找到了一个 link,它使用 TeamCity REST Api 添加标签,但它使用 curl 而我的构建服务器是 Windows。所以,我认为 PowerShell 可能可以做到。

使用 Invoke-WebRequest 我想出了以下脚本,其中自动替换了 TeamCity 构建参数:

$username = "%system.teamcity.auth.userId%"
$password = "%system.teamcity.auth.password%" | ConvertTo-SecureString -asPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username,$password)

Invoke-WebRequest `
   -Uri "%teamcity.serverUrl%/httpAuth/app/rest/builds/%teamcity.build.id%/tags" `
   -Credential $cred `
   -Method POST `
   -ContentType "application/xml" `
   -Body '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><tags><tag>%env.Environment%</tag></tags>' `
   -UseBasicParsing

TeamCity documentation 声明系统属性可用作凭据:

If you perform a request from within a TeamCity build, consider using teamcity.auth.userId/teamcity.auth.password system properties as credentials (within TeamCity settings you can reference them like %system.teamcity.auth.userId% and %system.teamcity.auth.password%)

但是,当我 运行 以上作为 Powershell 脚本构建步骤时,我收到 403 forbidden:

> [16:48:35][Step 1/1] Invoke-WebRequest : The remote server returned an
> error: (403) Forbidden. [16:48:35][Step 1/1] At line:1 char:1
> [16:48:35][Step 1/1] + Invoke-WebRequest ` [16:48:35][Step 1/1] +
> ~~~~~~~~~~~~~~~~~~~ [16:48:35][Step 1/1]     + CategoryInfo          :
> InvalidOperation: (System.Net.HttpWebRequest:Htt  [16:48:35][Step 1/1]
> pWebRequest) [Invoke-WebRequest], WebException [16:48:35][Step 1/1]   
> + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShe  [16:48:35][Step 1/1]
> ll.Commands.InvokeWebRequestCommand [16:48:35][Step 1/1]  
> [16:48:35][Step 1/1] Process exited with code 1 [16:48:35][Step 1/1]
> Step Powershell failed

我是否需要在 TeamCity 中启用某些功能以允许此用户 post 到 URL?

我有样本,我在 header 中发送凭据。

$ApiCredentials = New-Object System.Management.Automation.PSCredential($ApiUsername, (ConvertTo-SecureString $ApiPassword -AsPlainText -Force))

$ApiCredentials_ForHeader = $ApiUsername + ":" + $ApiPassword
$ApiCredentialsBase64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($ApiCredentials_ForHeader))

$ApiCredentialsHeader = @{};
$ApiCredentialsHeader.Add("Authorization", "Basic $ApiCredentialsBase64")

Invoke-RestMethod -Headers $ApiCredentialsHeader -Credential $ApiCredentials -Uri $Url -Method Post -ContentType $Type -Body $Data -TimeoutSec 30 -DisableKeepAlive;

希望对您有所帮助

%system.teamcity.auth.userId% + %system.teamcity.auth.password% 目前无效:https://youtrack.jetbrains.com/issue/TW-39206

明确指定凭据。如果你想隐藏密码,你可以用 spec password display='hidden' 创建配置参数。在这种情况下,参数值将不可用于读取,只能用于写入。此外,thi 参数将在日志中被屏蔽