Microsoft Azure Blob Storage Client Library for Python providing comprehensive APIs for blob storage operations.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Generate time-limited, secure access tokens for Azure Storage resources without exposing account keys. SAS tokens enable granular permission control for external access to storage accounts, containers, and blobs.
Generate account-level SAS tokens that provide access to multiple storage services and resource types within a storage account.
def generate_account_sas(account_name: str, account_key: str, resource_types: Union[ResourceTypes, str], permission: Union[AccountSasPermissions, str], expiry: Union[datetime, str], start: Optional[Union[datetime, str]] = None, ip: Optional[str] = None, *, services: Union[Services, str] = Services(blob=True), **kwargs) -> str:
"""
Generate an account-level shared access signature.
Args:
account_name (str): Storage account name
account_key (str): Storage account key
resource_types (Union[ResourceTypes, str]): Resource types the SAS can access
permission (Union[AccountSasPermissions, str]): Permissions granted by the SAS
expiry (Union[datetime, str]): SAS expiration time
Optional Args:
start (Optional[Union[datetime, str]]): SAS start time (default: now)
ip (Optional[str]): IP address or range restriction
services (Union[Services, str]): Storage services the SAS can access (default: blob service only)
Returns:
str: Account SAS token string
"""Usage Example:
from azure.storage.blob import generate_account_sas, ResourceTypes, AccountSasPermissions
from datetime import datetime, timedelta
# Generate account SAS valid for 1 hour
sas_token = generate_account_sas(
account_name="mystorageaccount",
account_key="account_key_here",
resource_types=ResourceTypes(service=True, container=True, object=True),
permission=AccountSasPermissions(read=True, write=True, list=True),
expiry=datetime.utcnow() + timedelta(hours=1),
protocol="https"
)Generate container-level SAS tokens that provide access to a specific container and its blobs.
def generate_container_sas(account_name: str, container_name: str, account_key=None, user_delegation_key=None, permission=None, expiry=None, start=None, policy_id=None, ip=None, protocol=None, **kwargs) -> str:
"""
Generate a container-level shared access signature.
Args:
account_name (str): Storage account name
container_name (str): Container name
account_key (str, optional): Storage account key
user_delegation_key (UserDelegationKey, optional): User delegation key for Azure AD auth
permission (ContainerSasPermissions, optional): Permissions granted by the SAS
expiry (datetime, optional): SAS expiration time
start (datetime, optional): SAS start time
policy_id (str, optional): Stored access policy identifier
ip (str, optional): IP address or range restriction
protocol (str, optional): Protocol restriction ('https' or 'https,http')
Note:
Must provide either account_key or user_delegation_key.
Must provide either permission/expiry or policy_id.
Returns:
str: Container SAS token string
"""Usage Example:
from azure.storage.blob import generate_container_sas, ContainerSasPermissions
# Generate container SAS with account key
sas_token = generate_container_sas(
account_name="mystorageaccount",
container_name="mycontainer",
account_key="account_key_here",
permission=ContainerSasPermissions(read=True, write=True, list=True),
expiry=datetime.utcnow() + timedelta(hours=2)
)
# Generate container SAS with stored access policy
sas_token = generate_container_sas(
account_name="mystorageaccount",
container_name="mycontainer",
account_key="account_key_here",
policy_id="my-stored-policy"
)Generate blob-level SAS tokens that provide access to a specific blob, including snapshots and versions.
def generate_blob_sas(account_name: str, container_name: str, blob_name: str, snapshot=None, version_id=None, account_key=None, user_delegation_key=None, permission=None, expiry=None, start=None, policy_id=None, ip=None, protocol=None, **kwargs) -> str:
"""
Generate a blob-level shared access signature.
Args:
account_name (str): Storage account name
container_name (str): Container name
blob_name (str): Blob name
snapshot (str, optional): Blob snapshot identifier
version_id (str, optional): Blob version identifier
account_key (str, optional): Storage account key
user_delegation_key (UserDelegationKey, optional): User delegation key for Azure AD auth
permission (BlobSasPermissions, optional): Permissions granted by the SAS
expiry (datetime, optional): SAS expiration time
start (datetime, optional): SAS start time
policy_id (str, optional): Stored access policy identifier
ip (str, optional): IP address or range restriction
protocol (str, optional): Protocol restriction ('https' or 'https,http')
Optional Keyword Args:
content_type (str, optional): Response content type override
content_encoding (str, optional): Response content encoding override
content_language (str, optional): Response content language override
content_disposition (str, optional): Response content disposition override
cache_control (str, optional): Response cache control override
Note:
Must provide either account_key or user_delegation_key.
Must provide either permission/expiry or policy_id.
Returns:
str: Blob SAS token string
"""Usage Example:
from azure.storage.blob import generate_blob_sas, BlobSasPermissions
# Generate blob SAS for read access
sas_token = generate_blob_sas(
account_name="mystorageaccount",
container_name="mycontainer",
blob_name="myblob.txt",
account_key="account_key_here",
permission=BlobSasPermissions(read=True),
expiry=datetime.utcnow() + timedelta(hours=1)
)
# Generate blob SAS with response headers override
sas_token = generate_blob_sas(
account_name="mystorageaccount",
container_name="mycontainer",
blob_name="document.pdf",
account_key="account_key_here",
permission=BlobSasPermissions(read=True),
expiry=datetime.utcnow() + timedelta(hours=1),
content_type="application/pdf",
content_disposition="attachment; filename=document.pdf"
)Define permissions for account-level SAS tokens across multiple storage services.
class AccountSasPermissions:
"""Account-level SAS permissions."""
def __init__(self, read=False, write=False, delete=False, list=False, add=False, create=False, update=False, process=False, delete_previous_version=False, tag=False, filter_by_tags=False, **kwargs):
"""
Initialize account SAS permissions.
Args:
read (bool): Read access to resources
write (bool): Write access to resources
delete (bool): Delete access to resources
list (bool): List access to resources
add (bool): Add access to resources
create (bool): Create access to resources
update (bool): Update access to resources
process (bool): Process access to resources
delete_previous_version (bool): Delete previous versions
tag (bool): Tag access to resources
filter_by_tags (bool): Filter by tags access
"""
@classmethod
def from_string(cls, permission: str) -> 'AccountSasPermissions':
"""Create permissions from permission string (e.g., 'rwdlacup')."""
def __str__(self) -> str:
"""Return permission string representation."""Define permissions for container-level SAS tokens.
class ContainerSasPermissions:
"""Container-level SAS permissions."""
def __init__(self, read=False, write=False, delete=False, list=False, add=False, create=False, delete_previous_version=False, tag=False, **kwargs):
"""
Initialize container SAS permissions.
Args:
read (bool): Read blobs in container
write (bool): Write blobs in container
delete (bool): Delete blobs in container
list (bool): List blobs in container
add (bool): Add blobs to container
create (bool): Create blobs in container
delete_previous_version (bool): Delete previous blob versions
tag (bool): Set/get blob tags
"""
@classmethod
def from_string(cls, permission: str) -> 'ContainerSasPermissions':
"""Create permissions from permission string (e.g., 'rwdl')."""
def __str__(self) -> str:
"""Return permission string representation."""Define permissions for blob-level SAS tokens.
class BlobSasPermissions:
"""Blob-level SAS permissions."""
def __init__(self, read=False, write=False, delete=False, add=False, create=False, delete_previous_version=False, tag=False, move=False, execute=False, **kwargs):
"""
Initialize blob SAS permissions.
Args:
read (bool): Read the blob
write (bool): Write to the blob
delete (bool): Delete the blob
add (bool): Add blocks to append blob
create (bool): Create the blob
delete_previous_version (bool): Delete previous versions
tag (bool): Set/get blob tags
move (bool): Move/rename the blob
execute (bool): Execute the blob (if executable)
"""
@classmethod
def from_string(cls, permission: str) -> 'BlobSasPermissions':
"""Create permissions from permission string (e.g., 'rwd')."""
def __str__(self) -> str:
"""Return permission string representation."""Specify which resource types an account-level SAS can access.
class ResourceTypes:
"""Resource types for account SAS."""
def __init__(self, service=False, container=False, object=False, **kwargs):
"""
Initialize resource types.
Args:
service (bool): Access to service-level operations
container (bool): Access to container operations
object (bool): Access to blob objects
"""
@classmethod
def from_string(cls, resource_types: str) -> 'ResourceTypes':
"""Create resource types from string (e.g., 'sco')."""
def __str__(self) -> str:
"""Return resource types string representation."""User delegation keys enable SAS generation with Azure Active Directory credentials instead of account keys.
class UserDelegationKey:
"""User delegation key for Azure AD-based SAS."""
signed_oid: str # Object ID of the user
signed_tid: str # Tenant ID
signed_start: datetime # Key validity start time
signed_expiry: datetime # Key validity end time
signed_service: str # Storage service version
signed_version: str # Signed version
value: str # Key value for signingUsage Example:
# Get user delegation key from service client (requires Azure AD auth)
service_client = BlobServiceClient(account_url, credential=azure_ad_credential)
user_delegation_key = service_client.get_user_delegation_key(
key_start_time=datetime.utcnow(),
key_expiry_time=datetime.utcnow() + timedelta(hours=1)
)
# Use delegation key to generate blob SAS
sas_token = generate_blob_sas(
account_name="mystorageaccount",
container_name="mycontainer",
blob_name="myblob.txt",
user_delegation_key=user_delegation_key,
permission=BlobSasPermissions(read=True),
expiry=datetime.utcnow() + timedelta(hours=1)
)SAS tokens can be used in several ways:
# Append to URL as query parameter
blob_url_with_sas = f"https://account.blob.core.windows.net/container/blob.txt?{sas_token}"
# Use with client constructors
blob_client = BlobClient.from_blob_url(blob_url_with_sas)
# Use with AzureSasCredential
from azure.core.credentials import AzureSasCredential
credential = AzureSasCredential(sas_token)
blob_client = BlobClient(account_url, container_name, blob_name, credential=credential)Enhance security by restricting SAS usage to specific IP addresses and protocols:
# Restrict to specific IP range and HTTPS only
sas_token = generate_blob_sas(
account_name="mystorageaccount",
container_name="mycontainer",
blob_name="myblob.txt",
account_key="account_key_here",
permission=BlobSasPermissions(read=True),
expiry=datetime.utcnow() + timedelta(hours=1),
ip="192.168.1.0/24", # IP range restriction
protocol="https" # HTTPS only
)Use stored access policies for easier SAS management and revocation:
# Create stored access policy on container
from azure.storage.blob import AccessPolicy, ContainerSasPermissions
access_policy = AccessPolicy(
permission=ContainerSasPermissions(read=True, write=True),
expiry=datetime.utcnow() + timedelta(days=1),
start=datetime.utcnow()
)
container_client.set_container_access_policy({
"my-policy": access_policy
})
# Generate SAS using stored policy
sas_token = generate_container_sas(
account_name="mystorageaccount",
container_name="mycontainer",
account_key="account_key_here",
policy_id="my-policy"
)Install with Tessl CLI
npx tessl i tessl/pypi-azure-storage-blob