首页 > 解决方案 > generate_blob_sas 创建无效的 SAS 令牌

问题描述

我正在更新一些使用 Microsoft 较旧的 azure-storage 模块并切换v12SDK 的脚本。

我遇到了为 blob 生成 SAS 令牌的问题。使用以下代码:

from datetime import datetime, timedelta
from azure.storage.blob import (
    BlobServiceClient,
    BlobSasPermissions,
    generate_blob_sas,
)

client = BlobServiceClient(account_url=account_url, credential=account_key)
token = generate_blob_sas(
            account_name=client.account_name,
            account_key=client.credential.account_key,
            container_name="tempcontainer",
            blob_name="test.txt",
            permissions=BlobSasPermissions(read=True),
            expiry=datetime.utcnow() + timedelta(hours=1),
        )

我收到如下所示的令牌:

se=2021-05-04T01%3A50%3A41Z&sv=2020-06-12&sr=b&sig=_________________________________________%3D

当我尝试使用下载资源时返回以下错误:

<Error>
  <link type="text/css" rel="stylesheet" id="dark-mode-custom-link"/>
  <link type="text/css" rel="stylesheet" id="dark-mode-general-link"/>
  <style lang="en" type="text/css" id="dark-mode-custom-style"/>
  <style lang="en" type="text/css" id="dark-mode-native-style"/>
  <Code>AuthenticationFailed</Code>
  <Message>
      Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:7c78e0c4-001e-010f-6b7f-40cd26000000 Time:2021-05-04T00:48:24.8329422Z
  </Message>
  <AuthenticationErrorDetail>sp is mandatory. Cannot be empty</AuthenticationErrorDetail>
</Error>

使用相同的帐户和凭据,我仍然能够使用旧版本成功生成 SAS 令牌:

from azure.storage.blob import BlockBlobService, ContainerPermissions

token = self.client.generate_blob_shared_access_signature(
    "tempcontainer",
    "test.txt",
    ContainerPermissions.READ,
    datetime.now() + duration,
)

它产生工作令牌,其中包含“sp”查询参数。

se=2021-06-03T16%3A57%3A59Z&sp=r&sv=2017-04-17&sr=b& sig=___________________________________________%3D

我还使用 Azure 存储资源管理器进行了测试,以验证我使用的帐户/密钥没有问题,并且我也能够通过该工具生成 SAS 链接。

这是pip list我的 venv 中安装的所有 azure 模块的输出:

azure-common                  1.1.25
azure-core                    1.13.0
azure-identity                1.3.1
azure-keyvault-secrets        4.1.0
azure-mgmt-core               1.2.2
azure-mgmt-keyvault           2.2.0
azure-storage-blob            12.8.1

生成这些 SAS 令牌的新 SDK 有什么问题吗?这是某种不同的令牌,还是我缺少一些额外的参数?也许用这个新版本生成 SAS 令牌的不同/更好的方法?

非常感谢您在此提供的任何帮助!

标签: pythonazureblob

解决方案


在您使用 V12 SDK 的代码中,对于generate_blob_sas函数,参数名称应permissionpermissions

这是我基于您共享的代码的测试代码:

from datetime import datetime, timedelta
from azure.storage.blob import (
    BlobSasPermissions,
    generate_blob_sas
)

token = generate_blob_sas(
            account_name='<account name>',
            account_key='<account key>',
            container_name='<container name>',
            blob_name='<blob name>',
            permission=BlobSasPermissions(read=True),
            expiry=datetime.utcnow() + timedelta(hours=1),
        )

print(token)

结果:

在此处输入图像描述 在此处输入图像描述


推荐阅读