azure-devopsgit-cloneazure-service-principal

How to use azure devops authorization bearer token and clone a repo?


I am trying to clone a repo using an authorization bearer token I created using a service connection in Azure. The service principal has reader access to the repo I'm trying to clone. And in Azure I've given the following API permissions for the AAD app (since this didn't help I'm not sure if this is necessary):

enter image description here

Setup the default organization and project: az devops configure --defaults organization="$org" project="$project"

$org is the azure devops organization and $project is the project where the git repo is.

Get the access token using the following command: $token = az account get-access-token --resource "499b84ac-1321-427f-aa17-267ca6975798" --query "accessToken" --output tsv

The above steps are done in a powershell script which is run using AzureCLI@2 task in the pipeline. The obtained token is saved in git config using the following command:

git config --local http.<repo base URL>.extraheader "AUTHORIZATION bearer: $token"

When the git clone command is run, I get the following error:

error: failed to execute prompt script (exit code 1)
fatal: could not read Username for '<repo URL>': No such file or directory

Any idea why I'm getting this error? Am I missing any steps?


Solution

  • You can get the devops repo url following doc:

    enter image description here

    Steps below:

    1. Create the service connection as you did, find the service principal and add it as contributor role +Basic access level of the target devops repo(if only clone the repo, project reader + basic access level permission is enough). So that the bearer token has permission to access the repo.

    2. DevOps pipeline yaml sample below. set at git config at global level.

    pool:
      vmImage: Windows-latest
    
    steps:
    - task: AzureCLI@2
      inputs:
        azureSubscription: 'ARMConn1'
        scriptType: 'ps'
        scriptLocation: 'inlineScript'
        inlineScript: |
          $token = az account get-access-token --resource "499b84ac-1321-427f-aa17-267ca6975798" --query "accessToken" --output tsv
          git config --global http.extraheader "AUTHORIZATION: Bearer $token"
          git clone https://<orgname>@dev.azure.com/<orgname>/<project>/_git/<reponame>
    

    enter image description here