0

I have an Azure Blob storage connection string in a config file, for example:

"Storage": "DefaultEndpointsProtocol=https;AccountName=xyz;AccountKey=abc==;EndpointSuffix=core.windows.net"

In the app, this is used to instanciate a BlobServiceClient, here is the registration happening in the Startup.cs:

  builder.Services.AddAzureClients(options => options.AddBlobServiceClient(configuration.GetValue<string>("Storage")));

This works and a BlobServiceClient can be injected in the constructor of a service and use it.

Now for a new scenario, I need to generate a Sas token. I want to use this solution Generate SAS token c# programmatically but it requires to create a new StorageSharedKeyCredential with the help of 2 parameters: accountName and accountKey.

Question

Since these values are present in the connection string, I could parse it somehow to get them, but probably there is a smarter way to retrieve separate accountName and accountKey values from a connection string or from a BlobServiceClient instance?

Or can I get a StorageSharedKeyCredential in an other way than creating it manually from accountName/accountKey, for example from a connection string?


Update for Gaurav Mantri's answer

var blobSasBuilder = new BlobSasBuilder()
{
    BlobContainerName = "containerName",
    BlobName = "fileName",
    ExpiresOn = DateTime.UtcNow.AddMinutes(15),
};

blobSasBuilder.SetPermissions(BlobSasPermissions.Read | BlobSasPermissions.Write);
Bruno
  • 4,685
  • 7
  • 54
  • 105

1 Answers1

1

You can make use of BlobBaseClient.GenerateSasUri method. Essentially your code would be something like:

var blobClient = new BlobBaseClient(connectionString, containerName, blobName);
var sasUri = blobClient.GenerateSasUri(/*blob SAS builder parameters*/);
Gaurav Mantri
  • 128,066
  • 12
  • 206
  • 241
  • 403 error happens when you use SAS token for an operation the permissions of which are not included in the token e.g try to upload blob with read permission in the token. I would recommend checking that. Otherwise, please ask a separate question with the code and I’ll take a look. – Gaurav Mantri Aug 20 '22 at 01:02