Search code examples
c#azure-blob-storageazure-managed-identity

Cannot generate container sas token using managed identities


Using c# I'm trying to generate SAS tokens for containers;

The identity I'm using has the following roles assigned to it

Storage Blob Data Contributor
Storage Blob Data Owner
Storage Account Contributor

When running the following code

//_blobServiceClient is instanciated using managed identity credentials

BlobContainerClient blobContainerClient = this._blobServiceClient.GetBlobContainerClient(blobContainerName);
await blobContainerClient.CreateIfNotExistsAsync(PublicAccessType.None).ConfigureAwait(false);

BlobSasBuilder sasBuilder = new BlobSasBuilder()
{
    BlobContainerName = blobContainerName,
    ExpiresOn = DateTime.UtcNow.AddDays(30)
};

sasBuilder.SetPermissions(BlobContainerSasPermissions.Read 
    | BlobContainerSasPermissions.List 
    | BlobContainerSasPermissions.Write
    | BlobContainerSasPermissions.Filter);

return blobContainerClient.GenerateSasUri(sasBuilder);

the blobContainerClient.CanGenerateSasUri property seem to be always set to false. Am I missing some roles?

is it even possible to generate container sas tokens using managed identities authentication?


Solution

  • the blobContainerClient.CanGenerateSasUri property seem to be always set to false.

    The reason it is coming as false is because you are using Managed Identity to generate a SAS token and this method will return true only when you are using Account Key for generating SAS token. (Reference)

    enter image description here

    is it even possible to generate container sas tokens using managed identities authentication?

    Yes, it is entirely possible to do so. However the process of generating the SAS token using Managed Identity is different. For this, you would first need to get a user delegation key (BlobServiceClient.GetUserDelegationKeyAsync Method) and then use that key to generate a SAS token. To learn more about it, please see this: https://learn.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas.