Create a user delegation SAS for a container with Python
A shared access signature (SAS) enables you to grant limited access to containers and blobs in your storage account. When you create a SAS, you specify its constraints, including which Azure Storage resources a client is allowed to access, what permissions they have on those resources, and how long the SAS is valid.
Every SAS is signed with a key. You can sign a SAS in one of two ways:
- With a key created using Microsoft Entra credentials. A SAS that is signed with Microsoft Entra credentials is a user delegation SAS. A client that creates a user delegation SAS must be assigned an Azure RBAC role that includes the Microsoft.Storage/storageAccounts/blobServices/generateUserDelegationKey action. To learn more, see Create a user delegation SAS.
- With the storage account key. Both a service SAS and an account SAS are signed with the storage account key. The client that creates a service SAS must either have direct access to the account key or be assigned the Microsoft.Storage/storageAccounts/listkeys/action permission. To learn more, see Create a service SAS or Create an account SAS.
Note
A user delegation SAS offers superior security to a SAS that is signed with the storage account key. Microsoft recommends using a user delegation SAS when possible. For more information, see Grant limited access to data with shared access signatures (SAS).
This article shows how to use Microsoft Entra credentials to create a user delegation SAS for a container using the Azure Storage client library for Python.
About the user delegation SAS
A SAS token for access to a container or blob may be secured by using either Microsoft Entra credentials or an account key. A SAS secured with Microsoft Entra credentials is called a user delegation SAS, because the OAuth 2.0 token used to sign the SAS is requested on behalf of the user.
Microsoft recommends that you use Microsoft Entra credentials when possible as a security best practice, rather than using the account key, which can be more easily compromised. When your application design requires shared access signatures, use Microsoft Entra credentials to create a user delegation SAS for superior security. For more information about the user delegation SAS, see Create a user delegation SAS.
Caution
Any client that possesses a valid SAS can access data in your storage account as permitted by that SAS. It's important to protect a SAS from malicious or unintended use. Use discretion in distributing a SAS, and have a plan in place for revoking a compromised SAS.
For more information about shared access signatures, see Grant limited access to Azure Storage resources using shared access signatures (SAS).
Assign Azure roles for access to data
When a Microsoft Entra security principal attempts to access blob data, that security principal must have permissions to the resource. Whether the security principal is a managed identity in Azure or a Microsoft Entra user account running code in the development environment, the security principal must be assigned an Azure role that grants access to blob data. For information about assigning permissions via Azure RBAC, see Assign an Azure role for access to blob data.
Set up your project
To work with the code examples in this article, follow these steps to set up your project.
Install packages
Install the following packages using pip install
:
pip install azure-storage-blob azure-identity
Set up the app code
Add the following import
directives:
from azure.identity import DefaultAzureCredential
from azure.storage.blob import (
BlobServiceClient,
ContainerClient,
BlobClient,
BlobSasPermissions,
ContainerSasPermissions,
UserDelegationKey,
generate_container_sas,
generate_blob_sas
)
Get an authenticated token credential
To get a token credential that your code can use to authorize requests to Blob Storage, create an instance of the DefaultAzureCredential class. For more information about using the DefaultAzureCredential class to authorize a managed identity to access Blob Storage, see Azure Identity client library for Python.
The following code snippet shows how to get the authenticated token credential and use it to create a service client for Blob storage:
# Construct the blob endpoint from the account name
account_url = "https://<storage-account-name>.blob.core.windows.net"
#Create a BlobServiceClient object using DefaultAzureCredential
blob_service_client = BlobServiceClient(account_url, credential=DefaultAzureCredential())
To learn more about authorizing access to Blob Storage from your applications with the Python SDK, see Authenticate Python apps to Azure services.
Get the user delegation key
Every SAS is signed with a key. To create a user delegation SAS, you must first request a user delegation key, which is then used to sign the SAS. The user delegation key is analogous to the account key used to sign a service SAS or an account SAS, except that it relies on your Microsoft Entra credentials. When a client requests a user delegation key using an OAuth 2.0 token, Blob Storage returns the user delegation key on behalf of the user.
Once you have the user delegation key, you can use that key to create any number of user delegation shared access signatures, over the lifetime of the key. The user delegation key is independent of the OAuth 2.0 token used to acquire it, so the token doesn't need to be renewed if the key is still valid. You can specify the length of time that the key remains valid, up to a maximum of seven days.
Use one of the following methods to request the user delegation key:
The following code example shows how to request the user delegation key:
def request_user_delegation_key(self, blob_service_client: BlobServiceClient) -> UserDelegationKey:
# Get a user delegation key that's valid for 1 day
delegation_key_start_time = datetime.datetime.now(datetime.timezone.utc)
delegation_key_expiry_time = delegation_key_start_time + datetime.timedelta(days=1)
user_delegation_key = blob_service_client.get_user_delegation_key(
key_start_time=delegation_key_start_time,
key_expiry_time=delegation_key_expiry_time
)
return user_delegation_key
Create a user delegation SAS for a container
Once you've obtained the user delegation key, you can create a user delegation SAS. You can create a user delegation SAS to delegate limited access to a container resource using the following method:
The user delegation key to sign the SAS is passed to the method as the user_delegation_key
argument. Allowed permissions are passed to the method as the permission
argument, and are defined in the ContainerSasPermissions class.
The following code example shows how to create a user delegation SAS for a container:
def create_user_delegation_sas_container(self, container_client: ContainerClient, user_delegation_key: UserDelegationKey):
# Create a SAS token that's valid for one day, as an example
start_time = datetime.datetime.now(datetime.timezone.utc)
expiry_time = start_time + datetime.timedelta(days=1)
sas_token = generate_container_sas(
account_name=container_client.account_name,
container_name=container_client.container_name,
user_delegation_key=user_delegation_key,
permission=ContainerSasPermissions(read=True),
expiry=expiry_time,
start=start_time
)
return sas_token
Use a user delegation SAS to authorize a client object
The following code example shows how to use the user delegation SAS created in the earlier example to authorize a ContainerClient object. This client object can be used to perform operations on the container resource based on the permissions granted by the SAS.
# The SAS token string can be appended to the resource URL with a ? delimiter
# or passed as the credential argument to the client constructor
sas_url = f"{container_client.url}?{sas_token}"
# Create a ContainerClient object with SAS authorization
container_client_sas = ContainerClient.from_container_url(container_url=sas_url)
Resources
To learn more about creating a user delegation SAS using the Azure Blob Storage client library for Python, see the following resources.
Code samples
REST API operations
The Azure SDK for Python contains libraries that build on top of the Azure REST API, allowing you to interact with REST API operations through familiar Python paradigms. The client library method for getting a user delegation key uses the following REST API operations:
- Get User Delegation Key (REST API)
Client library resources
See also
- Grant limited access to Azure Storage resources using shared access signatures (SAS)
- Create a user delegation SAS
Related content
- This article is part of the Blob Storage developer guide for Python. To learn more, see the full list of developer guide articles at Build your Python app.