Authenticate to Azure resources from Python apps hosted on-premises

Apps hosted outside of Azure (for example on-premises or at a third-party data center) should use an application service principal to authenticate to Azure when accessing Azure resources. Application service principal objects are created using the app registration process in Azure. When an application service principal is created, a client ID and client secret will be generated for your app. The client ID, client secret, and your tenant ID are then stored in environment variables so they can be used by the Azure SDK for Python to authenticate your app to Azure at runtime.

A different app registration should be created for each environment the app is hosted in. This allows environment specific resource permissions to be configured for each service principal and ensures that an app deployed to one environment doesn't talk to Azure resources that are part of another environment.

1 - Register the application in Azure

An app can be registered with Azure using either the Azure portal or the Azure CLI.

az ad sp create-for-rbac --name <app-name>

The output of the command will be similar to the following. Make note of these values or keep this window open as you'll need these values in the next steps and won't be able to view the password (client secret) value again.

{
  "appId": "00000000-0000-0000-0000-000000000000",
  "displayName": "msdocs-python-sdk-auth-prod",
  "password": "abcdefghijklmnopqrstuvwxyz",
  "tenant": "33333333-3333-3333-3333-333333333333"
}

2 - Assign roles to the application service principal

Next, you need to determine what roles (permissions) your app needs on what resources and assign those roles to your app. Roles can be assigned a role at a resource, resource group, or subscription scope. This example shows how to assign roles for the service principal at the resource group scope since most applications group all their Azure resources into a single resource group.

A service principal is assigned a role in Azure using the az role assignment create command.

az role assignment create --assignee {appId} \
    --scope /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName} \
    --role "{roleName}" 

To get the role names that a service principal can be assigned to, use the az role definition list command.

az role definition list \
    --query "sort_by([].{roleName:roleName, description:description}, &roleName)" \
    --output table

For example, to allow the service principal with the appId of 00000000-0000-0000-0000-000000000000 read, write, and delete access to Azure Storage blob containers and data in all storage accounts in the msdocs-python-sdk-auth-example resource group in the subscription with ID 11111111-1111-1111-1111-111111111111, you would assign the application service principal to the Storage Blob Data Contributor role using the following command.

az role assignment create --assignee 00000000-0000-0000-0000-000000000000 \
    --scope /subscriptions/11111111-1111-1111-1111-111111111111/resourceGroups/msdocs-python-sdk-auth-example \
    --role "Storage Blob Data Contributor"

For information on assigning permissions at the resource or subscription level using the Azure CLI, see the article Assign Azure roles using the Azure CLI.

3 - Configure environment variables for application

You must set the AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET environment variables for the process that runs your Python app to make the application service principal credentials available to your app at runtime. The DefaultAzureCredential object looks for the service principal information in these environment variables.

When using Gunicorn to run Python web apps in a UNIX server environment, environment variables for an app can be specified by using the EnvironmentFile directive in the gunicorn.server file as shown below.

[Unit]
Description=gunicorn daemon
After=network.target  
  
[Service]  
User=www-user
Group=www-data
WorkingDirectory=/path/to/python-app
EnvironmentFile=/path/to/python-app/py-env/app-environment-variables
ExecStart=/path/to/python-app/py-env/gunicorn --config config.py wsgi:app
            
[Install]  
WantedBy=multi-user.target

The file specified in the EnvironmentFile directive should contain a list of environment variables with their values as shown below.

AZURE_CLIENT_ID=<value>
AZURE_TENANT_ID=<value>
AZURE_CLIENT_SECRET=<value>

4 - Implement DefaultAzureCredential in application

To authenticate Azure SDK client objects to Azure, your application should use the DefaultAzureCredential class from the azure.identity package.

Start by adding the azure.identity package to your application.

pip install azure-identity

Next, for any Python code that creates an Azure SDK client object in your app, you'll want to:

  1. Import the DefaultAzureCredential class from the azure.identity module.
  2. Create a DefaultAzureCredential object.
  3. Pass the DefaultAzureCredential object to the Azure SDK client object constructor.

An example of this is shown in the following code segment.

from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient

# Acquire a credential object
token_credential = DefaultAzureCredential()

blob_service_client = BlobServiceClient(
        account_url="https://<my_account_name>.blob.core.windows.net",
        credential=token_credential)

When the above code instantiates the DefaultAzureCredential object, DefaultAzureCredential reads the environment variables AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET for the application service principal information to connect to Azure with.