Search code examples
c#azureazure-functionsazure-blob-storageazure-sas

How to get a Shared Access Signature on a Blob using the latest Azure SDK .NET API v12?


I used to be able to create a shared access signature on a Blob using the v11 Azure SDK API, like this:

var containerName = "mycontainer";
var blobName = "myblob";

CloudStorageAccount storageAccount 
 = CloudStorageAccount.Parse(<StorageConnectionString>);

CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

CloudBlobContainer container = blobClient.GetContainerReference(containerName);


SharedAccessBlobPermissions permission = SharedAccessBlobPermissions.Read;

TimeSpan clockSkew = TimeSpan.FromMinutes(15d);
TimeSpan accessDuration = TimeSpan.FromMinutes(15d);

var blobSAS = new SharedAccessBlobPolicy
{
    SharedAccessStartTime = DateTime.UtcNow.Subtract(clockSkew),
    SharedAccessExpiryTime = DateTime.UtcNow.Add(accessDuration) + clockSkew,
    Permissions = permissions
};

CloudBlockBlob blob = container.GetBlockBlobReference(blobName);

string sasBlobToken = blob.GetSharedAccessSignature(blobSAS);

...

I want to use the latest v12 .NET API which seems to replace CloudBlobClient by BlobServiceClient, CloudBlobContainer by BlobContainerClient and CloudBlockBlob by BlobClient.

However the method GetSharedAccessSignature that is available on a CloudBlockBlob instance is not available on a BlobClient instance.

Question

How to get a shared access signature from a BlobClient instance using the latest Azure SDK .NET API v12?


Solution

  • Sajeetharan's answer made me look for a BlobSasBuilder class, which actually exists.

    Here is how I can build one on the server:

    //  Creates a client to the BlobService using the connection string.
    var blobServiceClient = new BlobServiceClient(storageConnectionString);
    
    //  Gets a reference to the container.
    var blobContainerClient = blobServiceClient.GetBlobContainerClient(<ContainerName>);
    
    //  Gets a reference to the blob in the container
    BlobClient blobClient = blobContainerClient.GetBlobClient(<BlobName>);
    
    //  Defines the resource being accessed and for how long the access is allowed.
    var blobSasBuilder = new BlobSasBuilder
    {
        StartsOn = DateTime.UtcNow.Subtract(clockSkew), 
        ExpiresOn = DateTime.UtcNow.Add(accessDuration) + clockSkew,
        BlobContainerName = <ContainerName>,
        BlobName = <BlobName>,
    };
        
    //  Defines the type of permission.
    blobSasBuilder.SetPermissions(BlobSasPermissions.Write);
           
    //  Builds an instance of StorageSharedKeyCredential      
    var storageSharedKeyCredential = new StorageSharedKeyCredential(<AccountName>, <AccountKey>);
    
    //  Builds the Sas URI.
    BlobSasQueryParameters sasQueryParameters = blobSasBuilder.ToSasQueryParameters(storageSharedKeyCredential);
    

    Here is how to use it on the client side:

    //  Builds the URI to the blob storage.
    UriBuilder fullUri = new UriBuilder()
    {
        Scheme = "https",
        Host = string.Format("{0}.blob.core.windows.net", <AccountName>),
        Path = string.Format("{0}/{1}", <ContainerName>, <BlobName>),
        Query = sasQueryParameters.ToString()
    };
    
    //  Get an instance of BlobClient using the URI.
    var blobClient = new BlobClient(fullUri.Uri, null);
    
    //  Upload stuff in the blob.
    await blobClient.UploadAsync(stream);
    

    Addendum

    As mentioned by @one2012 in the comments, a page has been put up few months later after this answer showcasing all the features found in the Azure.Storage namespaces. The link can be useful to get more information.

    Update

    On the server-side, I have an Azure Function that is now connecting a Azure Storage with the Function's Managed Identity. When I connect the storage, I am not using an account anymore, only the endpoint of the storage:

    BlobContainerClient blobContainerClient = new(new Uri(containerEndpoint), new DefaultAzureCredential());  
    

    This makes the following part from the initial server code a bit trickier because I used to use the CloudStorageAccount.Credentials.GetExportKeys() method to get the account's key. When using the Managed Identity, it seems I do not have access to it anymore:

    //  Builds an instance of StorageSharedKeyCredential      
        var storageSharedKeyCredential = new StorageSharedKeyCredential(<AccountName>, <AccountKey>);
    

    It turns out I have to use User Delegation to build a SAS Uri:

    ...
    BlobServiceClient blobServiceClient = blobClient.GetParentBlobContainerClient().GetParentBlobServiceClient();
    
    UserDelegationKey userDelegationKey = await blobServiceClient.GetUserDelegationKeyAsync
    (
        DateTimeOffset.UtcNow,
        DateTimeOffset.UtcNow.AddMinutes(5d)
    );
                
    BlobUriBuilder blobUriBuilder = new (blobClient.Uri)
    {
        // Specify the user delegation key.
        Sas = blobSasBuilder.ToSasQueryParameters(userDelegationKey, blobServiceClient.AccountName)
    };
    
    string uri = blobUriBuilder.ToUri();