How to generate SAS token using python legacy SDK(2.1) without account_key or connection_string

Viewed 75

I am using python3.6 and azure-storage-blob(version = 1.5.0) and trying to use user assigned managed identity to connect to my azure storage blob from an Azure VM.The problem I am facing is I want to generate the SAS token to form a downloadable url. I am using blob_service = BlockBlobService(account name,token credential) to authenticate. But I am not able to find any methods which let me generate SAS token without supplying the account key. Also not seeing any way of using the user delegation key as is available in the new azure-storage-blob (versions>=12.0.0). Is there any workaround or I will need to upgrade the azure storage library at the end.

1 Answers

I tried to reproduce in my environment to generate SAS token without account key or connection string got result successfully.

Code:

    import datetime as dt
    import json
    import os
    from azure.identity import DefaultAzureCredential
    from azure.storage.blob import (
        BlobClient,
        BlobSasPermissions,
        BlobServiceClient,
        generate_blob_sas,
    )
    
    credential = DefaultAzureCredential(exclude_shared_token_cache_credential=True)
        
    storage_acct_name = "Accountname"
    container_name = "containername"
    blob_name = "Filename"
    
    url = f"https://<Accountname>.blob.core.windows.net"
    blob_service_client = BlobServiceClient(url, credential=credential)
    udk = blob_service_client.get_user_delegation_key(
        key_start_time=dt.datetime.utcnow() - dt.timedelta(hours=1),
        key_expiry_time=dt.datetime.utcnow() + dt.timedelta(hours=1))
    
    sas = generate_blob_sas(
        account_name=storage_acct_name,
        container_name=container_name,
        blob_name=blob_name,
        user_delegation_key=udk,
        permission=BlobSasPermissions(read=True),
        start = dt.datetime.utcnow() - dt.timedelta(minutes=15),
        expiry = dt.datetime.utcnow() + dt.timedelta(hours=2),
    )
    
    sas_url = (
        f'https://{storage_acct_name}.blob.core.windows.net/'
        f'{container_name}/{blob_name}?{sas}'
    )
    
    print(sas_url)

Output:

gnr

Make sure you need to add storage blob data contributor role as below:

enter image description here

Related