Connecting Azure Blob Storage account using Managed Identity
In the previous post, we saw that we can connect to Azure KeyVault from ASP.NET Core application using the default credentials. If you haven't read that, please find it here
Manage application settings with Azure KeyVault
But this is not a secure way of doing things obviously due to security concerns. In order to overcome this, the recommended approach is used to Managed Identity in Azure. This will work only if your application is hosted in Azure. It is similar to a service principal which connects on your app's behalf to communicate with other resources
Create Managed Identity
The first step is to create a Managed Identity resource in Azure and then give read permission for this identity in the Keyvault which you need to communicate
You can refer to the official documentation given below to perform this step
Managed identities for Azure resources
Connecting to KeyVault from ASP.NET Core Web App
In my sample code, I want to connect to a storage account using MI, I have added the necessary configuration entries is my appsettings.json. This can change depending our your requirement
"AzureStorage": {
"AccountName": "gab22demostorage",
"ContainerName": "file-container"
},
"AzureKeyVault": {
"keyvault-url": "https://gab22demo-rg.vault.azure.net/",
"mi-client-id": "your mi id here"
},
Now, in my method where I want to connect to the storage account, add the below code
var accountName = _configuration["AzureStorage:AccountName"];
var containerName = _configuration["AzureStorage:ContainerName"];
var miClientId = _configuration["AzureKeyVault:mi-client-id"];
// Construct the blob container endpoint from the arguments.
string containerEndpoint = $"https://{accountName}.blob.core.windows.net/{containerName}";
// Get a credential and create a client object for the blob container.
BlobContainerClient blobContainer = new BlobContainerClient(new Uri(containerEndpoint),
new ManagedIdentityCredential(miClientId));
foreach (var itm in products)
{
BlobClient blobClient = blobContainer.GetBlobClient($"uploads/{itm.ImageFileName}");
using (var memoryStream = new MemoryStream())
{
await blobClient.DownloadToAsync(memoryStream);
var bytes = memoryStream.ToArray();
var b64String = Convert.ToBase64String(bytes);
itm.ImageUri = "data:image/png;base64," + b64String;
}
}
What we are doing basically here is
- reading the configuration from appsettings.json file
- connecting to the storage account using MI
- iterates through the blob container to download the image file
No Comments
Connecting Azure Blob Storage account using Managed Identity
Posted 12/9/2022Securing Azure KeyVault connections using Managed Identity
Posted 11/26/2022Manage application settings with Azure KeyVault
Posted 11/9/2022Adding Serilog to Azure Functions created using .NET 5
Posted 4/3/2021Learn how to split log data into different tables using Serilog in ASP.NET Core
Posted 4/23/2020