Search code examples
azure-devopsazure-pipelinesazure-devops-rest-apiazure-authentication

How to sign in interactively as a Service Principal to access Azure Repo?


I have Azure Devops pipelines working nicely (YAML not GUI). The Service Principal has a secret that I have created (and stored in a Key Vault) to allow the pipeline to log in during the pipeline for 2 things that require REST API calls (az rest) and these require a "manual" login. This is working perfectly.

However, I now need the same Service Principal to read the commmit titles during the pipeline (the code and deployments are different projects). From what I have read, this needs more REST API calls (az rest). So, I have created the REST API calls in the CLI and run this under my account in the Cloud Console. This also works (after I have done an "az login" and logged in as me).

All I now need to do is repeat this under the context of the Service Principal (which already has permissions to the repo via the Project Administrators group - I will trim this down later once it works). So, I login as the SP and get a Bearer token. This all works fine.

The problem occurs when I call the REST API to access the commit details. I do an az rest to this URI:

az login --service-principal -u "<guid>" -p "<password>" --tenant "<guid>"
$request = "https://dev.azure.com/<org>/<project>/_apis/git/repositories/<repo>/commits/<commit-id>"
$accessToken = az account get-access-token --query "accessToken" --output tsv
$token = "Bearer $accessToken"
$headers = @{ Authorization = $token }
$comment = az rest --method get --headers ( $headers | ConvertTo-Json ) --uri $request --query "comment" --output tsv

I get an error: Please sign-in at least once as \\ in a web browser to enable access to the service

We know that the permissions are therefore working. However, my question is:

  1. How am I supposed to log in interactively as the service principal in a web browser?
  2. Is there a better way to retrieve the commit title from the repo? (In other words, am I disappearing down a rabbit hole?)

Solution

  • Instead of using a service principal, use the oauth token assigned to the job in Azure Pipelines.

    steps:
      - powershell: | 
          Write-Host "This is a script that could use $env:SYSTEM_ACCESSTOKEN"
          Write-Host "$env:SYSTEM_ACCESSTOKEN = $(System.AccessToken)"
        env:
          SYSTEM_ACCESSTOKEN: $(System.AccessToken)
    
    

    You may need to assign additional permissions.