Hello @Yi Zhan
To use Managed Identity, you need to grant the necessary permissions to the identity and then update your code to use the identity to access the storage account.
To grant the necessary permissions to the identity, you need to assign the "Storage Blob Data Contributor" role to the identity on the storage account. You can do this by following these steps:
- In the Azure portal, navigate to your storage account.
- Click on "Access control (IAM)" in the left-hand menu.
- Click on the "+ Add" button and select "Add role assignment".
- In the "Add role assignment" blade, select "Storage Blob Data Contributor" as the role.
- In the "Assign access to" section, select "User, group, or service principal".
- In the "Select" field, search for and select the name of your function app.
- Click on the "Save" button to assign the role to the identity. Once you have assigned the role to the identity, you can update your code to use the identity to access the storage account. You can do this by using the
DefaultAzureCredential
class from the@azure/identity
package to authenticate with the identity and then passing the resultingTokenCredential
object to theBlobServiceClient
constructor.
Here is an example of how you can update your code to use Managed Identity:
const { BlobServiceClient } = require("@azure/storage-blob");
const { DefaultAzureCredential } = require("@azure/identity");
module.exports = async function (context, myBlob)
{
const accountName = process.env["AzureWebJobsStorage__accountname"];
const containerName = "mycontainer";
const blobName = "myblob";
const credential = new DefaultAzureCredential();
const blobServiceClient = new BlobServiceClient( `https://${accountName}.blob.core.windows.net`, credential );
const containerClient = blobServiceClient.getContainerClient(containerName);
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
await blockBlobClient.upload(myBlob, myBlob.length);
};
In this example, we are using the DefaultAzureCredential
class to authenticate with the identity and then passing the resulting TokenCredential
object to the BlobServiceClient
constructor.