我正在尝试使用 SAS URLs 和 user delegation key 生成 Azure SDK for Python 以读取 blob。
如果我使用存储帐户密钥,以下代码有效,但如果我尝试使用用户委托密钥,则失败。
import datetime as dt
import json
import os
from azure.identity import DefaultAzureCredential
from azure.storage.blob import (
BlobClient,
BlobSasPermissions,
BlobServiceClient,
generate_blob_sas,
)
credential = DefaultAzureCredential(exclude_shared_token_cache_credential=True)
storage_acct_name = "XYZ_storage_account"
container_name = "XYZ_blob_container"
blob_name = "xyz_data.json"
url = f"https://{storage_acct_name}.blob.core.windows.net"
blob_service_client = BlobServiceClient(url, credential=credential)
udk = blob_service_client.get_user_delegation_key(
key_start_time=dt.datetime.utcnow() - dt.timedelta(hours=1),
key_expiry_time=dt.datetime.utcnow() + dt.timedelta(hours=1))
sas = generate_blob_sas(
account_name=storage_acct_name,
container_name=container_name,
blob_name=blob_name,
user_delegation_key=udk,
#account_key=os.getenv("STORAGE_ACCOUNT_ACCESS_KEY"),
permission=BlobSasPermissions(read=True),
start = dt.datetime.utcnow() - dt.timedelta(minutes=15),
expiry = dt.datetime.utcnow() + dt.timedelta(hours=2),
)
sas_url = (
f'https://{storage_acct_name}.blob.core.windows.net/'
f'{container_name}/{blob_name}?{sas}'
)
blob_client = BlobClient.from_blob_url(sas_url)
blob_data = blob_client.download_blob(encoding='UTF-8')
data = json.loads(blob_data.readall())
使用 UDK 时,出现以下错误:
“此请求无权使用此权限执行此操作。 ... 错误代码:AuthorizationPermissionMismatch”
让存储帐户密钥四处浮动对于安全性而言并不理想,因此我更愿意使用 UDK。
在 Azure 门户中,我可以查看存储帐户 |访问控制 (IAM) |查看我的访问权限并查看我的角色为“贡献者”,范围为“订阅(继承)”。
从 docs 看来,“贡献者”应该授予 require “generateUserDelegationKey”权限,但是... ?
答案 0 :(得分:1)
如评论中所述,为了通过用户委托密钥获得 SAS 令牌,用户应该具有适当的 data
相关 RBAC 角色存储帐户。
您收到此错误的原因是为用户分配了 Contributor
角色,该角色是 control plane
RBAC 角色。控制平面 RBAC 角色旨在管理资源(如存储帐户本身)而不是其中的数据。为了管理数据,必须为用户分配适当的数据 RBAC 角色。
可以在此处找到有关这些角色的更多信息:https://docs.microsoft.com/en-us/azure/storage/blobs/assign-azure-role-data-access?tabs=portal。