all Technical posts

Authenticate Azure DevOps Against its Own REST API

During Azure DevOps build and release pipelines, you might have the need to consult the Azure DevOps REST API. This blog explains how you can easily perform the authentication that is required to call that REST API.

Enable OAuth Authentication

First of all, you need to check the option Allow scripts to the OAuth token.  This enables scripts and other processes launched by tasks to access the OAuth token through the System.AccessToken variable.  This setting is somewhere hidden in the Additional options of the Agent Job:

Use the OAuth token inside the script

Within a PowerShell script you can now retrieve the System.AccessToken variable and use it to authenticate against the Azure DevOps REST API.  A simplified example:

#Set authorization headers
Write-Host Set authorization headers
$headers = @{ Authorization = “Bearer $env:SYSTEM_ACCESSTOKEN” }

#Invoke REST API
Write-Host Invoke REST API
Invoke-RestMethod $url -Method $method -Body $body -Headers $headers -ContentType ‘application/json’ -Verbose

Grant access to the Azure DevOps pipeline

In many cases, the Azure DevOps identity that sits behind the System.AccessToken has already the required access rights to perform the API call.  However, you might get an exception that states that you don’t have enough permissions.  In that scenario, I tried several options, but could only manage to solve it with the help of the product group on Twitter:

If you grant sufficient permissions to the Project Collection Build Service (<Account Name>), your REST API call will succeed.

Cheers,
Toon

Subscribe to our RSS feed

Hi there,
how can we help?

Got a project in mind?

Connect with us

Let's talk

Let's talk

Thanks, we'll be in touch soon!

Call us

Thanks, we've sent the link to your inbox

Invalid email address

Submit

Your download should start shortly!

Stay in Touch - Subscribe to Our Newsletter

Keep up to date with industry trends, events and the latest customer stories

Invalid email address

Submit

Great you’re on the list!