2

When using Azure Devops functions such as creating a new Repo or starting a pipeline is there any way to authenticate the user without an Access token through Powershell? The only other solution that I found is Azure CLI though I would prefer to Invoke the web API calls.

1 Answer 1

11

Actually, indeed you can auth the Azure DevOps REST API without using a PAT(personal access token), but you could not auth it without any access token. Even if you use the user account to auth, essentially it will generate an access token to auth.

For your requirement, if you want to use powershell to auth the REST API, you could use the script below.

Make sure you have installed the Az powershell module, and login with a user account which has the permission in your devops org via Connect-AzAccount.

Here is a sample to start the pipeline with Runs - Run Pipeline. This sample uses the Azure AD access token to auth, please note don't change the 499b84ac-1321-427f-aa17-267ca6975798 in the script, it is the well-known resource id of the DevOps REST API, it works for me.

$token = (Get-AzAccessToken -ResourceUrl "499b84ac-1321-427f-aa17-267ca6975798").Token
$URL = 'https://dev.azure.com/orgname/testpro1/_apis/pipelines/52/runs?api-version=6.0-preview.1'
$header = @{
    'Authorization' = 'Bearer ' + $token
    'Content-Type' = 'application/json'
}
$body = @"
  {
    "resources": {
        "repositories": {
            "self": {
                "refName": "refs/heads/main"
            }
        }
    }
  }
"@

Invoke-RestMethod -Method Post -Uri $URL -Headers $header -Body $body | ConvertTo-Json

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome. This allowed me to automatically create release branches across multiple repositories
Recent update in May MS changed the Get-AccessToken method to return SecureString. "For security purposes, the default output type has been changed from a plain text String to SecureString." So, the code 'Authorization' = 'Bearer ' + $token needs to change to 'Authorization' = 'Bearer ' + ($token | ConvertFrom-SecureString -AsPlainText). This is because one cannot concatenate String with SecureString.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.