Skip to content

Instantly share code, notes, and snippets.

@joelverhagen
Created April 5, 2024 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelverhagen/60e446c7e8b80762554505f7726ad1d8 to your computer and use it in GitHub Desktop.
Save joelverhagen/60e446c7e8b80762554505f7726ad1d8 to your computer and use it in GitHub Desktop.
Managed identities or user impersonation with WindowsAzure.Storage
using System;
using System.Linq;
using Azure.Core;
using Azure.Identity;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
internal class Program
{
private static void Main(string[] args)
{
var baseUri = new Uri("https://mystorageaccount.blob.core.windows.net/");
Console.WriteLine("Fetching token.");
var tokenCredential = new DefaultAzureCredential();
var accessToken = tokenCredential.GetToken(
new TokenRequestContext(new[] { new Uri(baseUri, "/.default").AbsoluteUri }));
Console.WriteLine($"Token expires in {accessToken.ExpiresOn - DateTimeOffset.UtcNow}");
// TODO: handle token renewal with TokenCredential overload
var blobClient = new CloudBlobClient(
baseUri,
new StorageCredentials(
new Microsoft.WindowsAzure.Storage.Auth.TokenCredential(accessToken.Token)));
var containers = blobClient.ListContainers();
Console.WriteLine($"Containers: {string.Join(", ", containers.Select(x => x.Name))}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment