How to create Azure Storage SAS token using DefaultAzureCredential class

Viewed 244

I want to create SAS token to download a blob stored in container in azure storage. I can easily generate SAS token using shared credential but this requires storage access key. How can I generate sas token using managed Identity.

        credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
        sasQueryParams, err := azblob.BlobSASSignatureValues{
            Protocol:      azblob.SASProtocolHTTPS,
            ExpiryTime:    time.Now().UTC().Add(4 * time.Hour),
            ContainerName: containerName,
            BlobName:      blobName,
            Permissions:   azblob.BlobSASPermissions{Add: false, 
    Read: true, Write: false}.String(),
    }.NewSASQueryParameters(credential)

1 Answers

How can I generate sas token using managed Identity?

You can generate it by using DefaultAzureCredential and the proper access to that blob in the storage container.

Connect to the storage account by using the Azure AD credentials of Default Azure Credential class.

Sample Code:

    var strgAccName = _configuration.GetValue<string>("YourStorageAccountName");
    var saUri = $"https://{strgAccName}.blob.core.windows.net";
    var blobServiceClient = new BlobServiceClient(new Uri(saUri), new DefaultAzureCredential());
    var blobContainerClient = blobServiceClient.GetBlobContainerClient(_configuration.GetValue<string>("YourContainerName"));
    var blobClient = blobContainerClient.GetBlobClient("YourImage.jpg"); 
    // We can issue the SAS token till a maximum of 7 days.
    var userDelegationKey =  blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow,
                                                                    DateTimeOffset.UtcNow.AddHours(4)); 
                                                            
    var sasBuilder = new BlobSasBuilder()
    {
        BlobContainerName = blobClient.BlobContainerName,
        BlobName = blobClient.Name,
        Resource = "b", // b: blob, c: container
        StartsOn = DateTimeOffset.UtcNow,
        ExpiresOn = DateTimeOffset.UtcNow.AddHours(4),
    };

    sasBuilder.SetPermissions(BlobSasPermissions.Read); 
    var blobUriBuilder = new BlobUriBuilder(blobClient.Uri)
    {
        Sas = sasBuilder.ToSasQueryParameters(userDelegationKey,blobServiceClient.AccountName)
    };
    // Read this in any view like `blobUriBuilder.ToUri().ToString();`
}

And re-check the delegated access is there or not for that blob. So, we don't use any access key and connection string for this.

Thanks to @Anupam Maiti for this Article, please refer this for step-by-step procedure.

Related