我正在使用以下代码获取 azure blob 服务的 token :
from azure.storage.blob import BlobServiceClient from azure.identity import InteractiveBrowserCredential, DeviceCodeCredential, ClientSecretCredential
credential = DeviceCodeCredential(authority="login.microsoftonline.com", tenant_id="***", client_id="***")
blobber = BlobServiceClient(account_url="https://***.blob.core.windows.net", credential=credential)
blobs = blobber.list_containers()
for b in blobs:
print(b)
它工作得很好。
但是,在某个时间范围内,用户可能需要多次调用 blob 服务。关键是进程可能会关闭并重新打开几次。
让用户在每次进程重新启动时都经历交互式 token 获取过程会非常烦人。我想保留 token 并在以后的流程中重复使用它直到它过期(假设持久性是安全的)。
我应该使用什么类型的凭证? ClientSecretCredential 不起作用。或者,也许有一个我不知道的 token 缓存机制。
编辑:
我转发了一个variation of this question .它也有一个有效的答案。 谢谢 Jim Xu。
最佳答案
根据我的研究,DeviceCodeCredential
不会缓存 token ——每个 get_token(*scopes, **kwargs)
调用都会开始一个新的身份验证流程。
根据您的需要,您可以使用ClientSecretCredential
。具体如何实现,请引用以下步骤
- 创建服务主体并为其分配 Azure RABC 角色(例如存储 Blob 数据所有者、存储 Blob 数据贡献者和存储 Blob 数据读取者)以执行 Azure AD 身份验证和访问 Azure Blob 存储。更多详情请引用document和 document
我使用 Azure CLI
#create a sevice pricipal and assign Storage Blob Data Contributor role at storage account level
az login
az ad sp create-for-rbac -n "MyApp" --role "Storage Blob Data Contributor" \
--scope "/subscriptions/<subscription>/resourceGroups/<resource-group>/providers/Microsoft.Storage/storageAccounts/<storage-account>" --sdk-auth
# just assign Storage Blob Data Contributor role at storage account level
az role assignment create --assignee <sp_name> --role "Storage Blob Data Contributor role"
--scope "/subscriptions/<subscription>/resourceGroups/<resource-group>/providers/Microsoft.Storage/storageAccounts/<storage-account>"
- 代码
from azure.identity import ClientSecretCredential
token_credential = ClientSecretCredential(
sp_tenant_id,
sp_application_id,
sp_application_secret
)
# Instantiate a BlobServiceClient using a token credential
from azure.storage.blob import BlobServiceClient
blob_service_client = BlobServiceClient(account_url=self.oauth_url, credential=token_credential)
blobs = blob_service_client.list_containers()
for b in blobs:
print(b)
关于python-3.x - 重用从 DeviceCodeCredential 获得的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60191387/