Home > front end >  How to get account name and account key from a connection string or a BlobServiceClient?
How to get account name and account key from a connection string or a BlobServiceClient?

Time:08-20

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);

CodePudding user response:

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*/);
  • Related