- 您还可以在脚本中设置授权",如下所示:(在脚本中对凭据进行了硬编码)
例如:
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)"
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?
解决方案
How did you set the Authorization in your script?
- 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)"
- 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)"
这篇关于TFS 2015 API-401-未经授权:由于凭据无效,访问被拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!