I m creating an API with Nodejs which creates Storage Account using Azure Identtiy and Arm-storage Sdk. The problem is that when ever I run the below code I get Authorization erorr which I cant seem to resolve. I have set all kinds of authorization but I keep getting this error on the Registered App in Azure AD.
Below is my code:
const storageAccountName = params.CustomerID;
const location =params.SelectedRegion;
// Initialize the Azure Storage Management client
const credentials = new DefaultAzureCredential({
managedIdentityClientId: process.env.AZURE_CLIENT_ID,
clientSecret: process.env.AZURE_CLIENT_SECRET,
tenantId: process.env.AZURE_TENANT_ID
});
// const credentials = new DefaultAzureCredential();
const storageClient = new StorageManagementClient(credentials, subscriptionId);
// Define the properties of the storage account
const storageAccountParameters = {
sku: {
name: "Standard_LRS",
},
kind: "StorageV2",
location: location,
accessTier: "Hot",
};
try {
// Create the storage account
const operationResponse = await storageClient.storageAccounts.beginCreateAndWait(
resourceGroupName,
storageAccountName,
storageAccountParameters
);`
}catch (err) {
console.error("Error creating Storage Account:", err.message);
throw new Error(`${err.message}`);
}
I have tried giving permissions on App Registration and Azure Ad. But still the error persists. The account I m using has contributor role so that shouldn't be the problem. The problem is with the App registered.
The above error tells us that you don't have proper permission to create the storage account.
In the code, you need to use clientsecretcredential
to create a storage account with a contributor role.
I have an app with name testvenkat
which has contributor
role like below:
Portal:
Now, you can use the below code to create storage using app registration.
Code:
const {ClientSecretCredential} = require("@azure/identity");
const { StorageManagementClient } = require("@azure/arm-storage");
const subscriptionId = "your-subscription-id";
const resourceGroupName = "your-resource-group-name";
const storageAccountName = "venkat678";
const location = "East US";
const credentials = new ClientSecretCredential(
"your-tenant-id",
"your-client-id",
"your-client-secret"
);
const storageClient = new StorageManagementClient(credentials, subscriptionId);
const storageAccountParameters = {
sku: {
name: "Standard_LRS",
},
kind: "StorageV2",
location: location,
accessTier: "Hot",
};
try {
const operationResponse = storageClient.storageAccounts.beginCreateAndWait(
resourceGroupName,
storageAccountName,
storageAccountParameters
);
console.log("Storage account created successfully");
} catch (err) {
console.error("Error creating storage account:", err.message);
}
Output:
Storage account created successfully
Portal:
Also, if you don't have contributor role to your app registration try to assign Storage account contributor role
.