TFS 2015 API - 401 - Unauthorized: Access is denied due to invalid credentials

孤人 提交于 2019-12-11 06:20:42

问题


I am trying to call the REST API to get a previous builds details but when I try to run the script that calls the API, I get the error in the title:

401 - Unauthorized: Access is denied due to invalid credentials

It's using the credentials of the Build Agent on the build server. The build server can see the TFS url because it's able to successfully build. And if I try to call the API using my credentials, it works. It just won't work with the account that the build agent is running under.

Any ideas?


回答1:


How did you set the Authorization in your script?

  1. You can Use the OAuth token to access the REST API

To enable your script to use the build process OAuth token, go to the Options tab of the build definition and select Allow Scripts to Access OAuth Token (Reference below screenshot to enable the option).

Below script works on my side:

$url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/builds/14?api-version=2.0"
Write-Host "URL: $url"
$result = Invoke-RestMethod -Uri $url -Headers @{
    Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "$result = $($result | ConvertTo-Json -Depth 1000)"

  1. You can also set the Authorization in script like below: (hardcoded your credentials in the script)

e.g :

Param(
   [string]$collectionurl = "http://server:8080/tfs/DefaultCollection",
   [string]$projectName = "ProjectName",
   [string]$keepForever = "true",
   [string]$BuildId = "8",
   [string]$user = "UserName",
   [string]$token = "Password"
)

# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))

$uri = "$($collectionurl)/$($projectName)/_apis/build/builds/$($BuildId)?api-version=2.0"
$result = Invoke-RestMethod -Uri $uri -Method Get -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

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



来源:https://stackoverflow.com/questions/50225499/tfs-2015-api-401-unauthorized-access-is-denied-due-to-invalid-credentials

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!