Key vault is a fully managed service in Azure to store secrets and keys using strong cryptographic algorithms or optional hardware based keys.
Steps to integrate in .NET 6 application -
- Create a resource group.
- Create a Key Vault app in the Azure portal.
- Install
az-cli
. - Login first time using the az cli by typing
az login
- Add Service principal for using az cli -
az ad sp create-for-rbac --name "<YOUR_SERVICE_PRINCIPAL_NAME>"
- The
az-cli
will return a JSON object on executing the above command which looks like (Store this for later use) -{ "appId": "<uuidv4>", "displayName": "<YOUR_SERVICE_PRINCIPAL_NAME>", "name": "<uuidv4>", "password": "<random_string>", "tenant": "<uuidv4>" }
- Head over to Access Policies tab in the Key vault app in Azure portal and select the Service Principal name in the dropdown and add
GET
andLIST
permissions. - Navigate to Secrets tab and add any application secrets.
- Copy the Vault URI in the Key vault app and add it into the
appsettings.json
file. - To authenticate we will use managed identities which will read 3 environment variables (
AZURE_CLIENT_ID
,AZURE_CLIENT_SECRET
, andAZURE_TENANT_ID
) to ascertain our identity. AZURE_CLIENT_ID
corresponds toappId
,AZURE_CLIENT_SECRET
corresponds topassword
, andAZURE_TENANT_ID
corresponds totenant
from step 6, copy this in to thelaunchSettings.json
file as we will be reading them as environment variables for the current process."environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "AZURE_CLIENT_ID": "<VALUE>", "AZURE_CLIENT_SECRET": "<VALUE>", "AZURE_TENANT_ID": "<VALUE>" }
- Install the following nugets for Azure SDK -
Azure.Extensions.AspNetCore.Configuration.Secrets
(For.AddAzureKeyVault
extension method for using Azure key vault as partial configuation)Azure.Identity
(ForDefaultAzureCredential
)Azure.Security.KeyVault.Secrets
(For creating key vault client)
- Inject
IConfiguration
into the controllers' constructor and fetch the value as any other configuration.