如何使用 Azure Python SDK 为容器创建共享访问签名

How to create a Shared Access Signature for a container with the Azure Python SDK

我正在尝试使用 Azure Python SDK 为 Azure 存储中的容器创建有效的共享访问签名 URL。我正在尝试生成它以立即生效,在 30 天后过期,并授予对整个容器(而不仅仅是 blob)的读写访问权限。下面的代码工作正常,最后打印了最后的 URL 。我还在门户中手动验证了容器和 blob 已成功创建。

但是,将 URL 粘贴到浏览器后,我收到以下错误消息:

<?xml version="1.0" encoding="UTF-8"?>

-<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:adecbe4e-0001-007c-0d19-40670c000000 Time:2015-12-26T20:10:45.9030215Z</Message>

<AuthenticationErrorDetail>Signature fields not well formed.</AuthenticationErrorDetail>

</Error>

看来问题一定出在这行代码上:

sasToken = blob_service.generate_shared_access_signature(containerName, None,SharedAccessPolicy(AccessPolicy(None, todayPlusMonthISO, "rw"), None))

这是完整的代码示例:

from azure.storage.blob import BlobService
import datetime
from azure.storage import AccessPolicy, CloudStorageAccount, SharedAccessPolicy

containerName = "testcontainer"
blobName = "testblob.txt"
azureStorageAccountName = "" # Removed for publishing to Whosebug
azureStorageAccountKey = "" # Removed for publishing to Whosebug
blob_service = BlobService(account_name=azureStorageAccountName, account_key=azureStorageAccountKey)
blob_service.create_container(containerName)
blob_service.put_block_blob_from_text(containerName,blobName,"Hello World")
today = datetime.datetime.utcnow()
todayPlusMonth = today + datetime.timedelta(30)
todayPlusMonthISO = todayPlusMonth.isoformat()
sasToken = blob_service.generate_shared_access_signature(containerName, None,SharedAccessPolicy(AccessPolicy(None, todayPlusMonthISO, "rw"), None))
url = "https://" + azureStorageAccountName + ".blob.core.windows.net/" + containerName + "/" + blobName + "?" + sasToken
print(url)

有什么解决办法吗?谢谢!

isoformat 方法将微秒附加到字符串,AFAICT 这在 ISO8601 中无效。

如果您这样修改代码:

todayPlusMonthISO = todayPlusMonth.replace(microsecond=0).isoformat() + 'Z'

生成的字符串生效。

例如,在您拥有之前:

2016-01-03T21:04:10.545430

更改会将其转换为有效的:

2016-01-03T21:04:10Z