Storage Account SAS while using Managed Identity

592 Views Asked by At

My application runs as Function App, in Azure. There is Storage Account, and App connects to the storage account using Managed Identity (so no connection string is used). Now I need to generate SAS Url for the Queue (which lives in the Storage Account). SAS Url should live 30 days.

But also, I need to make sure that storage account access keys are being rotated.

I follow this approach https://learn.microsoft.com/en-us/azure/key-vault/secrets/tutorial-rotation-dual?tabs=azure-cli to rotate the keys.

In case of connection string usage, it is clear how to swap the keys for SAS Url generation. We just need to change connection string when keys are rotated. Then we generate SAS Url in the code, and it is generated based on the key which is stored in the connection string.

But how to do it in case of Managed Identity access? How to select key which is used for SAS Url generation?

1

There are 1 best solutions below

5
Gaurav Mantri On

But how to do it in case of Managed Identity access? How to select key which is used for SAS Url generation?

In case of Managed Identity access, you do not need to use access keys. The SAS URL will use the permissions assigned to the managed identity for generating the SAS URL. The SAS URL you will be generating is called User Delegation SAS.

Here's the pseudo code for generating a user delegation sas token on a blob container with read permission. The sas token is valid for 1 hour.

var credentials = new ManagedIdentityCredential();
var blobServiceClient = new BlobServiceClient(new Uri("https://account.blob.core.windows.net", credentials));
var sasExpiry = DateTimeOffset.UtcNow.AddHours(1);
var userDelegationKey = await blobServiceClient.GetUserDelegationKeyAsync(null, sasExpiry, CancellationToken.None);
var containerClient = blobServiceClient.GetBlobContainerClient("containername");
var sasBuilder = new BlobSasBuilder()
{
    BlobContainerName = "containername",
    Resource = "c",
    ExpiresOn = sasExpiry
};
sasBuilder.SetPermissions(BlobSasPermissions.Read);
var blobUriBuilder = new BlobUriBuilder(containerClient.Uri)
{
    Sas = sasBuilder.ToSasQueryParameters(userDelegationKey,
        blobServiceClient.AccountName)
};
return blobUriBuilder.ToUri();