SOLVED

Authenticate Azure DevOps API Using Entra ID Managed Identity (Python)

Copper Contributor

I need my Python script to authenticate Azure DevOps API using the System Assigned Managed Identity of the VM it is running on.

 

To do that, I use azure.identity to get the managed identity token from management.azure.com resource URI (I tried different URIs and none seems to work including the ARM):

 

from azure.identity import ManagedIdentityCredential
credential = ManagedIdentityCredential()
token = credential.get_token('https://management.azure.com')
print(token.token)

 

 

And then use this token as Bearer token in the Authorization header.

It keeps on failing and returns me an HTML page.

 

However, when I get the token using PowerShell it works.

 

Connect-AzAccount -Identity
$token = Get-AzAccessToken
$token.Token

 

 

So clearly I don't get the token type Azure DevOps is expecting and I probably generate token against the wrong Resource URI.

I tried different resource URIs though like ARM, graph etc.. and I can't get it to work.

 

Any idea?

 

Edit:

Finally managed to do it, needed to scope it as Azure DevOps App

def GetMIToken():
    from azure.identity import ManagedIdentityCredential
    credential = ManagedIdentityCredential()
    token = credential.get_token('499b84ac-1321-427f-aa17-267ca6975798/.default')
    return token.token

 

1 Reply
best response confirmed by NirHazan (Copper Contributor)
Solution

Solution:

def GetMIToken():
    from azure.identity import ManagedIdentityCredential
    logging.info('Generating System Assigned Managed Identity token')
    credential = ManagedIdentityCredential()
    token = credential.get_token('499b84ac-1321-427f-aa17-267ca6975798/.default')
    logging.info('Successfully generated token')
    return token.token
1 best response

Accepted Solutions
best response confirmed by NirHazan (Copper Contributor)
Solution

Solution:

def GetMIToken():
    from azure.identity import ManagedIdentityCredential
    logging.info('Generating System Assigned Managed Identity token')
    credential = ManagedIdentityCredential()
    token = credential.get_token('499b84ac-1321-427f-aa17-267ca6975798/.default')
    logging.info('Successfully generated token')
    return token.token

View solution in original post