Azure Blob Storage: Download blob with SAS token


I am trying to download a file from a container in a Blob Storage account.

In my python script I am first creating a sas token and then trying to use this to download the file

from datetime import datetime, timedelta
from urllib.request import urlretrieve

from import (
accountName ="myaccountName"
accountKey = "myaccountKey"
containerName = "mycontainerName"
blob_name = "test.txt"
local_path = "testlocal.txt"

service = BlockBlobService(account_name=accountName, account_key=accountKey)
permission = BlobPermissions(_str="racwd")
sas = service.generate_blob_shared_access_signature(containerName, 'test.txt', permission, datetime.utcnow() + timedelta(hours=1),)

sas_service = BlockBlobService(
    sas_token= sas 

blob_uri = "" + containerName + "/" + blob_name +"?"+ sas

print (sas)
urlretrieve(blob_uri, local_path)

Running this produces the error

HTTPError: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

Does anyone know how I can create a sas token that gives download access to one specific file in my container?

Asked By: reachify



Please refer to the snippet of code as below , it works for me.

from datetime import datetime, timedelta

from import (

accountName = "***"
accountKey = "***"
containerName = "***"

blobService = BlockBlobService(account_name=accountName, account_key=accountKey)
sas_token = blobService.generate_container_shared_access_signature(containerName,ContainerPermissions.READ, datetime.utcnow() + timedelta(hours=1))
print sas_token

blobService = BlockBlobService(account_name=accountName, account_key=None, sas_token=sas_token)
blobService.get_blob_to_path(containerName, "1.png", "E://testLocal.png")

Hope it helps you.

Answered By: Jay Gong