python-3.x - 重用从 DeviceCodeCredential 获得的 token

标签 python-3.x azure-active-directory azure-blob-storage

我正在使用以下代码获取 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) 调用都会开始一个新的身份验证流程。 enter image description here

根据您的需要,您可以使用ClientSecretCredential。具体如何实现,请引用以下步骤

  1. 创建服务主体并为其分配 Azure RABC 角色(例如存储 Blob 数据所有者、存储 Blob 数据贡献者和存储 Blob 数据读取者)以执行 Azure AD 身份验证和访问 Azure Blob 存储。更多详情请引用documentdocument

我使用 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>"
  1. 代码
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)

enter image description here

关于python-3.x - 重用从 DeviceCodeCredential 获得的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60191387/

相关文章:

azure - 使用 Active Directory 集成身份验证向 Azure Sql 数据库添加具有特定权限的新用户

python-3.x - 使用 BLED112 加密狗连接到 BLE 模块并读/写 GATT 服务特征的 Python 代码

PyCharm 中的 python3 super() 新样式自动完成

azure - 创建 SQL 数据库时设置 Azure 管理员意味着什么?我应该为管理员选择哪个值?

azure - Get-AzureADServiceAppRoleAssignment 不会返回代表其他租户中 AAD 应用程序的 SP 的角色分配

c# - 调用 CloudBlobContainer.GetBlockBlobReference 是否会进行任何网络通信?

javascript - 如何使用 @azure/storage-blob sdk 附加 blob 文件? ( Node JS)

python - 使用新的 azure.storage.blob 包解决文件上传超时错误

python - 获取 postgresql 唯一日期的内存有效方式?

python - 选项卡的使用不一致