Search code examples
pythonazureaccess-token

Get Access Token for client profile Azure in Python


I'm looking for a way to get access token from a client profile when working with Azure using Python.

from azure.common.client_factory import get_client_from_cli_profile
from azure.mgmt.compute import ComputeManagementClient
client = get_client_from_cli_profile(ComputeManagementClient)

From the code I get the client profile context but how can I get access token from it?


Solution

  • I could find the method to get the access token from a client profile, to get the access token, you could use the adal, use which method depends on your requirement.

    For example, I get the access token of a service principal with the client credentials to access the Azure Management REST API, the given resource is https://management.azure.com/.

    import adal
    
    # Tenant ID for your Azure Subscription
    TENANT_ID = 'xxxxxxx'
    
    # Your Service Principal App ID
    CLIENT = 'xxxxxxx'
    
    # Your Service Principal Password
    KEY = 'xxxxxxx'
    
    
    subscription_id = 'xxxxxxx'
    
    authority_url = 'https://login.microsoftonline.com/'+TENANT_ID
    context = adal.AuthenticationContext(authority_url)
    token = context.acquire_token_with_client_credentials(
        resource='https://management.azure.com/',
        client_id=CLIENT,
        client_secret=KEY
    )
    
    print(token["accessToken"])
    

    enter image description here