python-3.xazureazure-blob-storageazure-sas

Python generate_container_sas function error with invalid base64-encoded string


I am trying to generator container shared access signature (SAS) using python. I am getting invalid base64 encoded error.

 sas_token = generate_container_sas(
            account_name=account_name,
            container_name=settings.AZURE_CONTAINER_NAME,
            account_key=account_key,
            permission=BlobSasPermissions(read=True),
            expiry=expiry_time,
            start=start_time
        )

Error message

Exception: Invalid base64-encoded string: number of data characters (85) cannot be 1 more than a multiple of 4

I tried to find reason on azure document but failed.


Solution

  • I tried in my environment and got the same error:

    Error: enter image description here

    The above error occurs when you pass the wrong access key in the generate_container_sas condition.

    You can get the access key from the portal:

    enter image description here

    When I use the below code with the correct access key. I can able to get the container SAS token with url.

    Code:

    from datetime import datetime,timedelta
    from azure.storage.blob import BlobServiceClient,ContainerSasPermissions,generate_container_sas
    
    account_name = 'Your-storage-account-name'
    container_name = 'your-container-name'
    account_key = 'your-account-key'
    
    expiry_time = datetime.utcnow() + timedelta(hours=1)
    
    
    permission = ContainerSasPermissions(read=True, write=True, delete=True, 
                                     list=True,delete_previous_version=True, tag=True)
    
    token = generate_container_sas(account_name=account_name,
                            container_name=container_name,
                            account_key=account_key,
                            permission=permission,
                            expiry=expiry_time)
    
    print(token)
    container_url = f"https://{account_name}.blob.core.windows.net/{container_name}?{token}"
    print(container_url)
    

    Output:

    SAS-token: se=2023-09-14T13%3A34%3A28Z&sp=rwdxlt&sv=2023-01-03&sr=c&sig=xxxxx
    https://venkat678.blob.core.windows.net/test?se=2023-09-14T13%3A34%3A28Z&sp=rwdxlt&sv=2023-01-03&sr=c&sig=xxxxxx
    

    enter image description here

    Reference:

    azure.storage.blob package | Microsoft Learn