Azure - Managed Identity

         

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.
  1. Create and assign a managed identity. Navigate to Azure CLI and execute below command

     az webapp identity assign --name "<webappName>" --resource-group "resourceGroup"

     2. On success we should get back below JSON in response. 

     {
    "principalId": "xxxx", "tenantId": "xxxxx", "type": "SystemAssigned" }

     3. To give your web app permission to do get and list operations on your key vault,                       execute below command

    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.

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...