如何通过Azure.Storage.Blobs.BlobServiceClient使用Azure托管身份?

时间:2020-02-14 08:24:32

标签: c# azure azure-storage-blobs

v11 SDK for .NET中,我能够使用托管身份令牌来访问Azure blob:

var token = await new AzureServiceTokenProvider().GetAccessTokenAsync("https://storage.azure.com/");
var tokenCredential = new TokenCredential(token);
var storageCredentials = new StorageCredentials(tokenCredential);
var blob = new CloudBlobContainer(new Uri("https://some_storage.blob.core.windows.net/some_container"), storageCredentials);

现在我想切换到v12 SDK,但不知道如何为BlobServiceClient做同样的事情。

1 个答案:

答案 0 :(得分:0)

我有一个样本:https://github.com/juunas11/managedidentity-filesharing/blob/8410ed3f3d4061de7d40531c025bf6e474489135/Joonasw.ManagedIdentityFileSharingDemo/Services/AzureBlobStorageService.cs#L80

以下是将它与Azure.Identity结合使用的方式:

client = new BlobServiceClient(
    new Uri($"https://{_options.AccountName}.blob.core.windows.net"),
    new ManagedIdentityCredential());

如果需要在本地针对Azure存储帐户运行,则可以使用自定义TokenCredential,例如:https://github.com/juunas11/Joonasw.ManagedIdentityDemos/blob/3501ee6fff416db7349807e588532da5c3dd24b1/Joonasw.ManagedIdentityDemos/Services/DemoService.cs#L45

自定义令牌凭证:https://github.com/juunas11/Joonasw.ManagedIdentityDemos/blob/master/Joonasw.ManagedIdentityDemos/Services/ManagedIdentityStorageTokenCredential.cs

对存储模拟器的使用:

client = new BlobServiceClient("UseDevelopmentStorage=true");