Azure dev ops

Azure DevOps REST calls using Microsoft interactive authentication

Azure DevOps REST calls using Microsoft interactive authentication

Making REST calls to Azure DevOps usually requires a valid username and an Azure DevOps PAT Token. While these are easy to obtain, they can be a right pain to manage. PATs have an expiry date and their value cannot be viewed after it has been initially created. So you end up either resetting it because its expired or if you didn’t record the value correctly.

I had a requirement recently to create a script to import YAML files into a DevOps repo and configure them as pipelines in the project. I had an existing script that ran as part of a devops pipeline, but this used the build agents token $(system.accesstoken) to authenticate. I could have just reused this script with a PAT, but other people were going to be using it.

After some searching I found this post on reddit. One of the responses by the user piense was perfect. They use Azure Cli to authenticate using the Microsoft interactive login process and then request a token to access Azure DevOps. This token is then used to authenticate the Invoke-RestMethod command. Absolute genius :)

    $url = "https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=5.1"

    az login --allow-no-subscriptions # use --use-device-code if the client won't have a browser

    $token = az account get-access-token --resource=499b84ac-1321-427f-aa17-267ca6975798 | ConvertFrom-Json

    $response = Invoke-RestMethod -Uri $url -Method Get -ContentType "application/json" -Headers @{ Authorization = "Bearer $($token.accessToken)" }

    Write-Output $response