Scenario: Use Azure Managed Identity to access Azure vault secrets
Solution:
Per Azure docs:
Azure Key Vault provides a way to store credentials and other secrets with increased security. But your code needs to authenticate to Key Vault to retrieve them. Managed identities for Azure resources help to solve this problem by giving Azure services an automatically managed identity in Azure Active Directory (Azure AD). You can use this identity to authenticate to any service that supports Azure AD authentication, including Key Vault, without having to display credentials in your code.
- Create and assign a managed identity. Navigate to Azure CLI and execute below command
az webapp identity assign --name "<webappName>" --resource-group "resourceGroup"
az webapp identity assign --name "<webappName>" --resource-group "resourceGroup"
{
"principalId": "xxxx",
"tenantId": "xxxxx",
"type": "SystemAssigned"
}
{
"principalId": "xxxx",
"tenantId": "xxxxx",
"type": "SystemAssigned"
}
az keyvault set-policy --name "<keyvaultName>" --object-id "<principalId>" --secret-permissions get list
az keyvault set-policy --name "<keyvaultName>" --object-id "<principalId>" --secret-permissions get list
4. In the Startup.cs file of the project add below
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Azure.Core;
var options = new SecretClientOptions()
{
Retry =
{
Delay= TimeSpan.FromSeconds(2),
MaxDelay = TimeSpan.FromSeconds(16),
MaxRetries = 5,
Mode = RetryMode.Exponential
}
};
var client = new SecretClient(new Uri("https://keyVaultName.vault.azure.net/"), new DefaultAzureCredential(),options);
KeyVaultSecret secret = client.GetSecret("secretName");
string secretValue = secret.Value;
5. Deploy the app to Azure.
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Azure.Core;
var options = new SecretClientOptions()
{
Retry =
{
Delay= TimeSpan.FromSeconds(2),
MaxDelay = TimeSpan.FromSeconds(16),
MaxRetries = 5,
Mode = RetryMode.Exponential
}
};
var client = new SecretClient(new Uri("https://keyVaultName.vault.azure.net/"), new DefaultAzureCredential(),options);
KeyVaultSecret secret = client.GetSecret("secretName");
string secretValue = secret.Value;
No comments:
Post a Comment