pythonazureazure-blob-storage

Generating SAS URL for Azure Blob Container with Proper Permissions


I'm attempting to generate a Shared Access Signature (SAS) URL for an Azure Blob storage container using Python and the Azure SDK. The SAS token is successfully generated, but when I try to use it to upload a file to the container, I encounter an "AuthorizationPermissionMismatch" error.

def generate_sas_url_for_container(strg_account, credentials, container_name, permissions, validity_hours):
    try:
        # Create BlobServiceClient using the storage account name and credentials
        blob_service_client = BlobServiceClient(account_url=f"https://{strg_account}.blob.core.windows.net/", credential=credentials)

        # Define permissions for the SAS token
        container_permissions = ContainerSasPermissions(read=permissions.read, create=permissions.create, list=permissions.list)
        user_delegation_key = blob_service_client.get_user_delegation_key(datetime.utcnow(), datetime.utcnow() + timedelta(hours=1))

        # Define expiry for the SAS token
        expiry = datetime.utcnow() + timedelta(hours=validity_hours)

        # Generate SAS token for the container
        sas_token = generate_container_sas(
            account_name=blob_service_client.account_name,
            user_delegation_key=user_delegation_key,
            container_name=container_name,
            account_key=None,
            permission=container_permissions,
            expiry=expiry,
            sv="2020-08-04"
        )
        sas_url = f"https://{blob_service_client.account_name}.blob.core.windows.net/{container_name}?{sas_token}"
        return sas_url
    except Exception as e:
        print(f"Error generating SAS URL for container: {e}")
        return None

And here's the error message I'm encountering when trying to use the generated SAS URL to upload a file:

<?xml version="1.0" encoding="utf-8"?><Error><Code>AuthorizationPermissionMismatch</Code><Message>This request is not authorized to perform this operation using this permission.
RequestId:a6cfe60c-501e-0095-40bf-a00
Time:2024-05-14T05:26:24.9759212Z</Message></Error>

Solution

  • encoding="utf-8"?><Error><Code>AuthorizationPermissionMismatch</Code><Message>This
    request is not authorized to perform this operation using this
    permission. RequestId:a6cfe60c-501e-0095-40bf-a00
    Time:2024-05-14T05:26:24.9759212Z</Message></Error> ```
    

    The above error occurs when you don't have proper permission to upload the file to Azure Blob Storage.

    You can use the code below to upload a file to Azure Blob Storage with correct permissions using generated sas url.

    Corrected Code:

    from datetime import datetime, timedelta
    from azure.storage.blob import BlobServiceClient, BlobClient, generate_container_sas, ContainerSasPermissions
    from azure.identity import DefaultAzureCredential
    
    def generate_sas_url_for_container(strg_account, credentials, container_name, permissions, validity_hours):
        try:
            blob_service_client = BlobServiceClient(account_url=f"https://{strg_account}.blob.core.windows.net/", credential=credentials)
            user_delegation_key = blob_service_client.get_user_delegation_key(datetime.utcnow(), datetime.utcnow() + timedelta(hours=1))
            expiry = datetime.utcnow() + timedelta(hours=validity_hours)
            sas_token = generate_container_sas(
                account_name=blob_service_client.account_name,
                user_delegation_key=user_delegation_key,
                container_name=container_name,
                permission=permissions,
                expiry=expiry,
                protocol="https"
            )
            sas_url = f"https://{blob_service_client.account_name}.blob.core.windows.net/{container_name}/{blob_name}?{sas_token}"
            return sas_url
        except Exception as e:
            print(f"Error generating SAS URL for container: {e}")
            return None
    
    def upload_file_to_container_with_sas_url(sas_url_with_blob_name, file_path):
        try:
            blob_client = BlobClient.from_blob_url(sas_url_with_blob_name)
            with open(file_path, "rb") as data:
                blob_client.upload_blob(data)
            return True
        except Exception as e:
            print(f"Error uploading file to container: {e}")
            return False
    
    strg_account = "venkat123"
    container_name = "test"
    file_path = r"C:\Users\Downloads\important.png"
    blob_name = "sample.png"
    permissions = ContainerSasPermissions(read=True, write=True, delete=True, list=True)
    validity_hours = 1
    credentials = DefaultAzureCredential()
    
    sas_url_with_blob_name = generate_sas_url_for_container(strg_account, credentials, container_name, permissions, validity_hours)
    upload_file_to_container_with_sas_url(sas_url_with_blob_name, file_path)
    

    The above code is executed and the file is uploaded using the sas url.

    Output: File Uploaded Successfully