azure-devopsazure-web-app-serviceazure-repos

Is it possible to acquire an access token for app service with a system-assigned managed identity?


I want to access Azure Repos from my app service with a system-assigned managed identity.

According to this post, it is possible to access Azure Repos git with an access token but I can't find how to acquire an access token from my app service with a system-assigned managed identity.

I think it also needs to grant permission to Azure DevOps resources to my app service for acquiring an access token.

I tried that

var token = tokenCredential.getTokenSync(
            new TokenRequestContext().addScopes("https://app.vssps.visualstudio.com/.default"));

and access to git with this url.

https://[the access token]@dev.azure.com/orgname/projname/_git/reponame

It resulted an unauthorized error.


Solution

  • I tried with Azure VM which has system-managed identity, it can work on my side.

    Steps below:

    1. Please add contributor role of the subscription for the system-managed identity, otherwise it will report error for azure login command. enter image description here
    2. Please add the identity to the DevOps organization and target project. enter image description here

    The doc has shared sample command to get access token for service principal and managed-identity.

    1. install azure cli, restart a new PS window, use command az login --identity to login.

    2. After login, you can get the accesstoken:

    $accessToken = az account get-access-token --resource 499b84ac-1321-427f-aa17-267ca6975798 --query "accessToken" --output tsv
    

    You can put the token in the url to repo or use for rest api :

    enter image description here

    Since you are using app service, and system-managed identity only works on the azure resource, you could need to login with identity in app service and request the access token in the app service.