Skip to content

Latest commit

 

History

History
59 lines (47 loc) · 2.96 KB

tutorial-connect-app-access-storage-javascript.md

File metadata and controls

59 lines (47 loc) · 2.96 KB
title description services author manager ms.service ms.topic ms.date ms.author ms.reviewer ms.devlang ms.custom ms.subservice
Tutorial - JavaScript Web app accesses storage by using managed identities | Azure
In this tutorial, you learn how to access Azure Storage for a JavaScript app by using managed identities.
storage, app-service-web
rwike77
CelesteDG
app-service
tutorial
07/31/2023
ryanwi
stsoneff
javascript
azureday1, devx-track-azurecli, devx-track-azurepowershell, subject-rbac-steps, devx-track-dotnet, devx-track-js, AppServiceConnectivity
web-apps

Tutorial: Access Azure services from a JavaScript web app

[!INCLUDE tutorial-content-above-code]

Access Blob Storage

The DefaultAzureCredential class from @azure/identity package is used to get a token credential for your code to authorize requests to Azure Storage. The BlobServiceClient class from @azure/storage-blob package is used to upload a new blob to storage. Create an instance of the DefaultAzureCredential class, which uses the managed identity to fetch tokens and attach them to the blob service client. The following code example gets the authenticated token credential and uses it to create a service client object, which uploads a new blob.

To see this code as part of a sample application, see StorageHelper.js in the:

JavaScript example

const { DefaultAzureCredential } = require("@azure/identity");
const { BlobServiceClient } = require("@azure/storage-blob");
const defaultAzureCredential = new DefaultAzureCredential();

// Some code omitted for brevity.

async function uploadBlob(accountName, containerName, blobName, blobContents) {
    const blobServiceClient = new BlobServiceClient(
        `https://${accountName}.blob.core.windows.net`,
        defaultAzureCredential
    );

    const containerClient = blobServiceClient.getContainerClient(containerName);

    try {
        await containerClient.createIfNotExists();
        const blockBlobClient = containerClient.getBlockBlobClient(blobName);
        const uploadBlobResponse = await blockBlobClient.upload(blobContents, blobContents.length);
        console.log(`Upload block blob ${blobName} successfully`, uploadBlobResponse.requestId);
    } catch (error) {
        console.log(error);
    }
}

[!INCLUDE tutorial-clean-up-steps]

[!INCLUDE tutorial-content-below-code]