There is a configuration in the Azure DevOps build pipeline which enable the scripts and other process launched by tasks to access the OAuth token through the SYSTEM.ACCESS.TOKEN variable. When access to the system access token is enabled it is possible to use $env:SYSTEM_ACCESSTOKEN environment variable in the task scripts, that you are executing in a build pipeline job.
We are going to execute following script using the PowerShell task in the pipeline. The script lists the builds in the current project. This script get the REST API URL and execute it using authentication from SYSTEM_ACCESSTOKEN. Finally,the outcome will be printed as a json output. You can see in the invoke rest method call header information, the system access token is passed as a bearer token.
$url = $env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI + $env:SYSTEM_TEAMPROJECTID + "/_apis/build/builds?api-version=5.1" Write-Host "URL: $url" $pipeline = Invoke-RestMethod -Uri $url -Headers @{ Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" } Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
If you try to execute the script without enabling the OAuth configuration in the pipeline $env:SYSTEM_ACCESSTOKEN doesn't have a value. So, script fails due to authentication issues.Following image shows the output when you execute the command without enabling the OAuth config in the build agent phase. It is unable to read data from the REST API without authentication.
Let's try to execute the same script after enabling the OAuth configuration in agent phase of the Azure DevOps build.
With enabled OAuth configuration it will return the requested values successfully.
If you are enabling OAuth token configuration in build pipelines, you can execute scripts without creating a PAT or using other authentications in the script. This post explained the OAuth token configuration available in the Azure DevOps pipeline and the use of it.
No comments:
Post a Comment