Search code examples
reactjsazureazure-active-directoryazure-storageazure-appservice

How to get azure blob storage data into react app that is hosted on azure app service


Hi I am working on react project ,I want to download huge files ( more than 2.5gb) from azure blob storage to react application , ( scenario is when user click on export button I have text files in azure blob storage I want them to be downloaded to local system ) , I have been looking at few approaches, since I am new to azure I am bit confused

using azure AD we can get access to azure blob storage but since my application is hosted on app service how we can connect these two together or we can have direct access to files through azure app services ?

approach I am currently looking at : here


Solution

  • If all the resources are from azure, then we should use manage identity or service principle (which also use manage identity under the hood) link in your case.

    In your case, you have two azure resources

    1. Azure blob storage
    2. App Service (which hosted as reactjs application) So Here is there is step by step explanation to how you connect and read blob

    In AppService(which hosted as reactjs application)

    1. Go to your Appservice
    2. Then Click on Identity in Left panel
    3. Then On System assigned managed identity
    4. After clicking save button then it generate Object Id. enter image description here

    In Azure Blob Storage

    1. Go to Your blob storage account

    2. Clicked Access Control(IAM)

    3. Click Role Assignment (RBAC)

    4. Click Add > Add Role assignment enter image description here

    5. Select Role as per your need like Storage Blob Data Reader

    6. Click Next > Select Managed Identity > Select Member

    7. Then Select your Subscription then App Service

    8. Then List of Managed identity are shown > Select your App Service one which need to connect with storage

    9. Then click on Select and then Next enter image description here

    10. Then You get the below screen. Match object id which generated in step 4 to below grid enter image description here

    11. Then Click Next > Next > Review + assign

    Now In React Js Application

    1. We can add these two Dependencies in package.json and do an npm i to install. enter image description here
    2. Now connect blob storage with DefaultAzureCredential from @azure/identity package :- when we give permission /access of one azure to another azure resource directly using service principle or managed identity then we use default azure credential then azure automatically validate them. Code For Import package
                    import { DefaultAzureCredential } from "@azure/identity";
                   // we're using these objects from the storage sdk - there are others for different needs
                   import { BlobServiceClient, BlobItem } from "@azure/storage-blob";
    
    1. Create service client and container
                   const blobStorageClient = new BlobServiceClient(
                    // this is the blob endpoint of your storage acccount. Available from the portal 
                   // they follow this format: <accountname>.blob.core.windows.net for Azure global
                   // the endpoints may be slightly different from national clouds like US Gov or Azure China
                     "https://<your storage account name>.blob.core.windows.net/",
                       new DefaultAzureCredential()
                     )
    
                 // this uses our container we created earlier
            var containerClient = blobStorageClient.getContainerClient("your container name");
    
    1. Get list of blob
            let blobs = containerClient.listBlobsFlat();
            for await (const blob of blobs) {
             console.log(`Blob ${i++}: ${blob.name}`);
      }
    
    1. Download blob
    const blobClient = containerClient.getBlobClient(blobName);
    
      // Get blob content from position 0 to the end
      // In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody
      const downloadBlockBlobResponse = await blobClient.download();
      const downloaded = (
        await streamToBuffer(downloadBlockBlobResponse.readableStreamBody)
      ).toString();
      console.log("Downloaded blob content:", downloaded);
    
      // [Node.js only] A helper method used to read a Node.js readable stream into a Buffer
      async function streamToBuffer(readableStream) {
        return new Promise((resolve, reject) => {
          const chunks = [];
          readableStream.on("data", (data) => {
            chunks.push(data instanceof Buffer ? data : Buffer.from(data));
          });
          readableStream.on("end", () => {
            resolve(Buffer.concat(chunks));
          });
          readableStream.on("error", reject);
        });
      }
    

    For More Details, Go through the below links

    1. Azure Storage Blob client library for JavaScript - version 12.12.0
    2. Quickstart: Manage blobs with JavaScript SDK in Node.js