Maxim Tkachenko
Maxim Tkachenko

Reputation: 5808

How to use Azure managed identity with Azure.Storage.Blobs.BlobServiceClient?

In v11 SDK for .NET I was able to use managed identity tokens to get access to 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);

Now I want to switch to v12 SDK and can't understand how to do the same for BlobServiceClient.

Upvotes: 1

Views: 15185

Answers (1)

juunas
juunas

Reputation: 58873

I have a sample: https://github.com/juunas11/managedidentity-filesharing/blob/8410ed3f3d4061de7d40531c025bf6e474489135/Joonasw.ManagedIdentityFileSharingDemo/Services/AzureBlobStorageService.cs#L80

Here is how it is used with Azure.Identity:

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

If you need to run against an Azure Storage account locally, you can use a custom TokenCredential, like here: https://github.com/juunas11/Joonasw.ManagedIdentityDemos/blob/3501ee6fff416db7349807e588532da5c3dd24b1/Joonasw.ManagedIdentityDemos/Services/DemoService.cs#L45.

Custom TokenCredential: https://github.com/juunas11/Joonasw.ManagedIdentityDemos/blob/master/Joonasw.ManagedIdentityDemos/Services/ManagedIdentityStorageTokenCredential.cs.

Usage against Storage Emulator:

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

Upvotes: 6

Related Questions