How to download a json file to Blob storage container using keys or connection string

Gabe 1 Reputation point
2023-11-09T16:15:35.04+00:00

Dear Microsoft do you have any tutorial on how to download a json file to Blob storage container using Access keys or connection string from the storage account instead of Shared access tokens. I am having a hard time updating storage account(dev, UAT and Prod) and expiring date.

Azure Storage Accounts
Azure Storage Accounts
Globally unique resources that provide access to data management services and serve as the parent namespace for the services.
2,302 questions
Azure Synapse Analytics
Azure Synapse Analytics
An Azure analytics service that brings together data integration, enterprise data warehousing, and big data analytics. Previously known as Azure SQL Data Warehouse.
3,818 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Anand Prakash Yadav 845 Reputation points Microsoft Vendor
    2023-11-13T12:06:35.22+00:00

    Hello Gabe,

    Thank you for posting your query here!

    I understand that you are trying to download a json file from Blob storage container using Access keys or connection string from the storage account instead of Shared access tokens.

    Here is a JavaScript code that uses the @azure/storage-blob library to download a blob from Azure Blob Storage. The code provided is using a connection string for authentication.

    const { BlobServiceClient } = require('@azure/storage-blob');
    const fs = require("fs");
    
    const connectionString = "<your-connection-string>"; // Replace with your actual connection string
    const containerName = "<your-container-name>"; // Replace with your actual container name
    const blobName = "<your-blob-name>"; // Replace with your actual blob name
    
    const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString);
    const containerClient = blobServiceClient.getContainerClient(containerName);
    const blobClient = containerClient.getBlobClient(blobName);
    
    // Download the blob
    const downloadBlockBlobResponse = await blobClient.download();
    
    // Convert the readable stream to a string
    const downloadedContent = await streamToString(downloadBlockBlobResponse.readableStreamBody);
    
    console.log("Downloaded blob content:", downloadedContent);
    
    // Function to convert a readable stream to a string
    async function streamToString(readableStream) {
      return new Promise((resolve, reject) => {
        const chunks = [];
        readableStream.on("data", (data) => {
          chunks.push(data.toString());
        });
        readableStream.on("end", () => {
          resolve(chunks.join(""));
        });
        readableStream.on("error", reject);
      });
    }
    
    

    Please note that using keys in code is not considered a recommended practice for security reasons. It's generally better to use Azure Managed Identities or Shared Access Signatures (SAS) for better security and easier rotation. If possible, consider using Azure Key Vault to store and manage secrets securely.

    As you are facing issue with SAS token due to expiry, I would recommend checking the following article to configure SAS expiration policy: https://learn.microsoft.com/en-us/azure/storage/common/sas-expiration-policy?tabs=azure-portal#how-to-configure-a-sas-expiration-policy

    You can also upload and download data between your local machine and Azure Storage accounts with the help of Azure Storage Explorer, you can connect it to Storage accounts using connection strings: https://learn.microsoft.com/en-us/azure/vs-azure-tools-storage-manage-with-storage-explorer?tabs=windows#account-name-and-key

    Please let us know if you have any further queries. I’m happy to assist you further.


    Please do not forget to "Accept the answer” and “up-vote” wherever the information provided helps you, this can be beneficial to other community members.

    1 person found this answer helpful.
    0 comments No comments

  2. Michael McKechney 85 Reputation points Microsoft Employee
    2023-11-09T16:56:09.3166667+00:00

    You don't mention a preferred language but here is an example in C# to both upload and download a file to/from blob storage. It uses the Azure.Storage.Blob NuGet SDK and dynamically builds the connection string with the storage account name and account key.
    Ideally, you would keep your key secure in an Azure KeyVault or secured configuration file, but this should get you started.

    using Azure.Storage.Blobs;
    using System.IO;
    using System.Threading.Tasks;
    
    public class BlobStorageService
    {
        private string storageAccountName = "<Your Storage Account Name>";
        private string storageAccountKey = "<Your Storage Account Key>";
        private string containerName = "<Your Container Name>";
    
        public async Task DownloadFromBlob(string fileName)
        {
            string connectionString = $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={storageAccountKey};EndpointSuffix=core.windows.net";
            var blobClient = new BlobClient(connectionString, containerName, fileName);
            BlobDownloadInfo download = await blobClient.DownloadAsync();
    
            using (FileStream file = File.OpenWrite(fileName))
            {
                await download.Content.CopyToAsync(file);
            }
        }
    
        public async Task UploadToBlob(string filePath, string blobName)
        {
            string connectionString = $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={storageAccountKey};EndpointSuffix=core.windows.net";
            var blobClient = new BlobClient(connectionString, containerName, blobName);
    
            using (FileStream file = File.OpenRead(filePath))
            {
                await blobClient.UploadAsync(file, true);
            }
        }
    }
    
    
    
    0 comments No comments