Use Managed Identity to Get Access Token for HTTP Request

Kaytee Flick 0 Reputation points Microsoft Employee
2024-08-07T21:36:35.9466667+00:00

Hello,

I need to acquire an access token to make an https request for an Azure web app using Synapse system managed identity.

Before switching to MI due to security requirements, I got the access token with this code

token= auth_context.acquire_token_with_client_credentials(resource, client_id, client_secret)

In databricks I am able to use this code with the databricks MI to get a token:

from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
cred = ManagedIdentityCredential()
cred.get_token(resource)

However, this code returns an error when run in a Synapse note with MI enabled:User's image I also looking into using the mssparkutils.credentials.getToken(), but it is not available for this audience type.

What method is available to get an access token using MI for a webapp?

Thanks!

Azure Synapse Analytics
Azure Synapse Analytics
An Azure analytics service that brings together data integration, enterprise data warehousing, and big data analytics. Previously known as Azure SQL Data Warehouse.
5,006 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Vinodh247 24,001 Reputation points MVP
    2024-08-08T10:00:13.1033333+00:00

    Hi,

    You can try to utilize the azure Identity library, which simplifies the process of obtaining tokens. This is the simple and straight forward for token acquisition.

    Use the following Python code snippet to obtain an access token using the Managed Identity. Before that make sure 'azure-identity' is installed in your env.

    from azure.identity import ManagedIdentityCredential
    from azure.core.credentials import AccessToken
    
    # Define the resource for which you need the token
    resource = "https://<your-web-app-name>.azurewebsites.net"
    
    # Create a Managed Identity Credential instance
    credential = ManagedIdentityCredential()
    
    # Acquire the token
    token: AccessToken = credential.get_token(resource)
    
    # Use the token for your HTTP requests
    access_token = token.token
    print(access_token)
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.