首页 > 解决方案 > 在 Python 中为 Azure Blob 存储中的目录生成 SAS 令牌

问题描述

我正在尝试使用 Python 来限制不同用户可以访问的 Azure 存储的哪些部分。

我一直在寻找可以为存储容器中的特定目录生成 SAS 令牌的代码。我希望在我的目录上生成一个 SAS 令牌,可以让我访问它包含的文件/blob。(就像它在 azure.portal 上的工作方式一样,我可以在其中右键单击我的目录并按“生成 SAS”。但是我找不到任何可以存档的 Python 代码。我能找到的只有以下 3 个功能:

generate_account_sas()
generate_container_sas()
generate_blob_sas()

在这里找到:https ://docs.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob?view=azure-python

我已经尝试使用“generate_blob_sas()”函数,但使用我的目录名称而不是文件/blob。

from datetime import datetime, timedelta
from azure.storage.blob import BlobClient, generate_blob_sas, BlobSasPermissions

account_name = 'STORAGE_ACCOUNT_NAME'
account_key = 'STORAGE_ACCOUNT_ACCESS_KEY'
container_name = 'CONTAINER_NAME'
blob_name = 'NAME OF MY DIRECTORY'

def get_blob_sas(account_name,account_key, container_name, blob_name):
    sas_blob = generate_blob_sas(account_name=account_name, 
                                container_name=container_name,
                                blob_name=blob_name,
                                account_key=account_key,
                                permission=BlobSasPermissions(read=True),
                                expiry=datetime.utcnow() + timedelta(hours=1))
    return sas_blob

blob = get_blob_sas(account_name,account_key, container_name, blob_name)
url = 'https://'+account_name+'.blob.core.windows.net/'+container_name+'/'+blob_name+'?'+blob

但是,当我尝试使用此 url 时,我得到以下响应:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
   <Code>AuthenticationFailed</Code>
   <Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:31qv254a-201e-0509-3f26-8587fb000000 Time:2021-07-30T09:37:21.1142028Z</Message>
   <AuthenticationErrorDetail>Signature did not match. String to sign used was rt 2021-07-30T10:08:37Z /blob/my_account/my_container/my_directory/my_file.png 2020-06-12 b </AuthenticationErrorDetail>
</Error>

我还有其他方法可以在目录上生成 SAS 令牌吗?

标签: pythonazureazure-blob-storageazureportalsas-token

解决方案


根据您的描述,您的存储帐户似乎是Data Lake Gen2. 如果是这种情况,那么您将需要使用不同的 SDK。

您使用的 SDK 适用于 Azure Blob 存储(非 Data Lake Gen2)帐户,其中文件夹是虚拟文件夹,而不是真实文件夹。

您想要使用的 SDKazure-storage-file-datalake和您想要用于在目录上生成 SAS 令牌的方法将是generate_file_system_sas.


推荐阅读