title: TeamCity REST Api returns 403 using system credentials
body: <p>When I run a build on TeamCity, I want to tag the build with an environment variable. I hoped this might be straightforward but it seems there is no built-in way to do it. I found a <a href="http://blog.minodudd.com/2014/01/automatically-pin-and-tag-builds-in-teamcity/" rel="nofollow">link</a> which uses the TeamCity REST Api to add the tag, but it uses <code>curl</code> and my build server is Windows. So, I figured PowerShell can probably do it.</p>
  
  <p>Using <code>Invoke-WebRequest</code> I've come up with the following script, where TeamCity build parameters are substituted automatically:</p>
  
  <pre><code>$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 '&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;&lt;tags&gt;&lt;tag&gt;%env.Environment%&lt;/tag&gt;&lt;/tags&gt;' `
     -UseBasicParsing
  </code></pre>
  
  <p>The <a href="https://confluence.jetbrains.com/display/TCD8/REST+API#RESTAPI-RESTAuthentication" rel="nofollow">TeamCity documentation</a> states that the system properties can be used as credentials:</p>
  
  <blockquote>
    <p>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%)</p>
  </blockquote>
  
  <p>However, when I run the above as a Powershell script build step, I receive a 403  forbidden:</p>
  
  <pre><code>&gt; [16:48:35][Step 1/1] Invoke-WebRequest : The remote server returned an
  &gt; error: (403) Forbidden. [16:48:35][Step 1/1] At line:1 char:1
  &gt; [16:48:35][Step 1/1] + Invoke-WebRequest ` [16:48:35][Step 1/1] +
  &gt; ~~~~~~~~~~~~~~~~~~~ [16:48:35][Step 1/1]     + CategoryInfo          :
  &gt; InvalidOperation: (System.Net.HttpWebRequest:Htt  [16:48:35][Step 1/1]
  &gt; pWebRequest) [Invoke-WebRequest], WebException [16:48:35][Step 1/1]   
  &gt; + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShe  [16:48:35][Step 1/1]
  &gt; ll.Commands.InvokeWebRequestCommand [16:48:35][Step 1/1]  
  &gt; [16:48:35][Step 1/1] Process exited with code 1 [16:48:35][Step 1/1]
  &gt; Step Powershell failed
  </code></pre>
  
  <p>Do I need to enable something in TeamCity to allow this user to post to the URL?</p>