Unable to authenticate against Azure DevOps _apis/distributedtask/variablegroups using PAT - powershell

I'm running a simple call to Azure DevOps API using Powershell:
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "{USER}","{PAT}")))
$url = "https://dev.azure.com/{ORG_NAME}/{PROJECT_NAME}/_apis/distributedtask/variablegroups/{ID}?api-version=5.0-preview.1"
Invoke-RestMethod -Uri $url -Method Get -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
The error is shown after:
Invoke-RestMethod: Response status code does not indicate success: 401 (Unauthorized).
Trying to figure out what's wrong, all is configured according to this and this articles.
The strange is that running a call against API without specifying the project is processed without errors:
$url2 = "https://dev.azure.com/{ORG_NAME}/_apis/projects?api-version=2.0"
Invoke-RestMethod -Uri $url2 -Method Get -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
Response:
count value
----- -----
5 {#{id=xxxxxxx-89f3-46b0-af7e-xxxxxxx; name=Xxxxx; description=F…

It seems your PAT is not authorized to access the Variable groups.
You can go to your PAT edit page to check if the PAT was assigned at least the Read permission for Variable groups. See below screenshot.
Grant the proper permission scope for your PAT, and try calling the rest api again.

Related

need to add authentication header to azure devops api request

I'm trying to get information on my latest builds by sending a GET request to the Azure DevOps REST Api. I'm using Azure DevOps Server 2020 with the Patch 1 update. I need to add an authorization header to the request. The header I added is not working.
I'm doing the request in Powershell. Here's my code:
$PAT = 'personal access token'
$ENCODED = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($PAT))
$headers = #{
Authorization="Basic $ENCODED"
}
Invoke-RestMethod -Uri [azure devops server url]/[project name]/_apis/build/latest/Build?api-version=5.0 -Method Get -Headers $headers
When I run the code I get the error: Invoke Method: The format of value [PAT] is invalid
UPDATE:
I updated the header syntax. Now the reponse I get:
Invoke-RestMethod:
TF400813: Resource not available for anonymous access. Client authentication required. - Azure DevOps Server
I also tried passing my Azure DevOps username and password in the header like this:
$headers = #{
Authorization="Basic [domain\username]:[password]"
}
and I got this in response:
Invoke-RestMethod: Response status code does not indicate success: 401 (Unauthorized).
Do I have to enable some setting in Azure DevOps?
I usually reference to this demo to run REST API in PowerShell, it can work fine:
$uri = "request URI"
$pat = "personal access token"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $pat)))
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", ("Basic {0}" -f $base64AuthInfo))
$headers.Add("Content-Type", "application/json")
. . .
$body = "{
. . .
}"
Invoke-RestMethod -Uri $uri -Headers $headers -Body $body -Method POST
In your case, the issue seems is caused by the encoding. Try using ASCII or UTF8, instead of Unicode.
To view more details, you can see "Use personal access tokens".

Capture commit count per pull request in Azure DevOps

I would like to get info on the number of commits per pull request. For now, semi-automated would be fine. Just looking for a simple approach, say, a PowerShell script. I'll likely need to create similar types of reports with different data in the future.
Does any approach lend itself to such a quick and dirty approach with Azure DevOps data?
There is a special Rest API for this: Pull Request Commits - Get Pull Request Commits:
GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}/commits?api-version=5.1
So, simple PowerShell script:
$pat = "YOUR-PERSONAL-ACCESS-TOKEN"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,"$pat")))
$headers = #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$url = "https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}/commits?api-version=5.1"
$commitsCount = (Invoke-RestMethod -Method Get -Uri $url -Headers $headers -Body $jsonBody -ContentType 'application/json').count

How to get status of the release (success, failure) with powershell using Azure DevOps Rest API

I am using post method to create release in Azure DevOps:
$url = "https://vsrm.dev.azure.com/"+$organization+"/"+$project+"/_apis/release/releases?api-version=5.1"
$body = #{definitionId = 9} | ConvertTo-Json -Depth 4
Invoke-RestMethod -Uri $url -Method POST -Body $body -ContentType "application/json" -Headers #{Authorization = ("Basic {0}" -f $base64AuthInfo)}
My pipeline is simple with single stage which executes automatically. Release creation and execution works fine.
But how to get status of my stage/s using powershell and REST API. I need to keep executing script while Release is in progress and initiate script failure if any of the stages fails.
Any ideas?
Using DefinitionID and EnvironmentIDs (you will get this from your initial POST response), you can query the last release and check for "deploymentStatus" value in intervals and exit when the status changes to "succeeded/failed/cancelled".
(collectionURL)/(teamproject)/_apis/Release/deployments?definitionId="+RELEASE_DEFINITIONID+"&definitionEnvironmentId="+RELEASE_DEFINITIONENVIRONMENTID?api-version=1.0

VSTS build history for a Build definition

I have a VSTS build definitions in our project, Can i get the build results (passed/failed) that ran using that definition (builds started running using the definition since last 6 months) ?
Currently i am only getting last 20 build information ran from that build definition.
You can get it through Build REST API with PowerShell: Get a list of builds.
For example:
param(
[string]$sinceDate,
[string]$token,
[string]$defId
)
$uri="https://[acccount.visualstudio.com/DefaultCollection/[project]/_apis/build/builds?definitions=$defId&deletedFilter=1&minFinishTime=$sinceDate"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "test",$token)))
$result= Invoke-RestMethod -Method Get -Uri $Uri -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$statusResult=$result.value | select-object -Property id,buildNumber,result
Arguments:
-sinceDate "12/1/2017" -token "[personal access token]" -defId "94"

VSTS build running locally - error: "Microsoft Internet Explorer. Enhanced Security Configuration"

I'm running Windows 10 and making a script to handle/start VSTS builds.
Sample call (overriding properties for testing):
$env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI = "https://mytenancy.visualstudio.com/"
$env:SYSTEM_TEAMPROJECTID = "Project1"
$env:SYSTEM_DEFINITIONID = 5
#$env:SYSTEM_ACCESSTOKEN = "mytoken" - uncomment when running locally
$url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/definitions/$($env:SYSTEM_DEFINITIONID)?api-version=2.0"
Write-Host "URL: $url"
$definition = Invoke-RestMethod -Uri $url -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "Definition = $($definition | ConvertTo-Json -Depth 100)"
"Authenticated"
This script works fine on the server, but if I uncomment the $env:SYSTEM_ACCESSTOKEN and run locally, I get the following error:
Microsoft Internet Explorer\u0026#39;s Enhanced Security Configuration
is currently enabled on your environment. This enhanced level of
security prevents our web integration experiences from displaying or
performing correctly. To continue with your operation please disable
this configuration or contact your administrator.
I'm running Windows 10.
I've tried many things, including:
Turning off as much security as possible in Internet Options.
Fresh Token
Converting the token to a secure string
Converting to a Base64 string as detailed in the answer to this post
How can I authenticate locally?
EDIT (following accepted answer)
The accepted answer solved the problem. I think the two key points here were:
The correct encoding in conversion to Base64
Changing authentication from Bearer to Basic when running in this way (locally).
Final code:
$user = "[username]"
$accessToken="[token]"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$accessToken)))
$env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI = "https://mytenancy.visualstudio.com/"
$env:SYSTEM_TEAMPROJECTID = "Project1"
$checkBuildUrl = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$($env:SYSTEM_TEAMPROJECTID)/_apis/build/builds/$($requestedBuildId)?api-version=2.0"
$buildStatus = Invoke-RestMethod -Uri $checkBuildUrl -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
Create a new access token and refer to this code to call the REST API through PowerShell:
$user = "[anything]"
$accessToken="[access token]"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$accessToken)))
...
Invoke-RestMethod -Uri $uri -Method Post -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Body $bodyJson
Regarding enhanced security, there is a similar issue:
Enhanced Security Error while Visual Studio Team Services Rest API