通过连接字符串访问 Azure Blob 存储时身份验证失败

Authentication Failure when Accessing Azure Blob Storage through Connection String

当我们尝试使用 python v12 sdk 与 Azure Blob Storage v12.5.0 和 Azure core 1.8.2 从连接字符串创建 azure blob 客户端时,出现身份验证失败错误。

我用过 天蓝色存储 blob == 12.5.0 蔚蓝核心 == 1.8.2

我尝试使用带有 Python v12 SDK 的连接字符串访问我的 blob 存储帐户,但收到上述错误。我 运行 所在的环境是 NixShell 中的 python venv。

调用blob_upload的代码如下:

blob_service_client = BlobServiceClient(account_url=<>,credential=<>)    
blob_client = blob_service_client.get_blob_client(container=container_name,
        blob=file)

我打印出来blob_client,看起来很正常。但是下一行upload_blob报错

with open(os.path.join(root,file), "rb") as data:
                    blob_client.upload_blob(data)

报错信息如下

    File "<local_address>/.venv/lib/python3.8/site-packages/azure/storage/blob/_upload_helpers.py", in upload_block_blob
    return client.upload(
  File "<local_address>/.venv/lib/python3.8/site-packages/azure/storage/blob/_generated/operations/_block_blob_operations.py", in upload
    raise models.StorageErrorException(response, self._deserialize)
azure.storage.blob._generated.models._models_py3.StorageErrorException: Operation returned an invalid status 'Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.'

所以我打印出了http put请求到azure blob存储,得到了[403]的响应值

下面的代码我用和你一样的版本都能很好的运行

from azure.storage.blob import BlobServiceClient
blob=BlobServiceClient.from_connection_string(conn_str="your connect string in Access Keys")
with open("./SampleSource.txt", "rb") as data:
    blob.upload_blob(data)

请检查您的 connect-string,并检查您的 PC 时间。

有一个关于错误的类似问题:AzureStorage Blob Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature


更新:

我试过这段代码,得到了同样的错误:

from azure.storage.blob import BlobServiceClient
from azure.identity import DefaultAzureCredential

token_credential = DefaultAzureCredential()

blob_service_client = BlobServiceClient(account_url="https://pamelastorage123.blob.core.windows.net/",credential=token_credential)    
blob_client = blob_service_client.get_blob_client(container="pamelac", blob="New Text Document.txt")

with open("D:/demo/python/New Text Document.txt", "rb") as data:
    blob_client.upload_blob(data)

然后我用AzureCliCredential()代替DefaultAzureCredential()。我使用 az login 通过 Azure CLI 进行身份验证。并且有效。

如果使用环境凭证,需要设置变量。无论如何,我建议您使用 特定凭据 而不是 DefaultAzureCredential.

有关 Azure 身份的更多详细信息,请参阅 here