Fetches secret key from Azure key vault using REST API inside a .NET Core app. Seems pretty useful for building secure Azure applications so I thought I would document the process to the best of my ability.
- Git
- Get started with Azure
- Set and retrieve a secret from Azure Key Vault using the Azure portal
- Download .NET
- Azure CLI
-
Clone project:
PS C:\> git clone https://github.com/OpticGenius/FetchKeyVaultSecret.git
-
cd
into solution directory:PS C:\> cd FetchKeyVaultSecret
-
Build project dependencies:
PS C:\> dotnet build
-
Login to your Azure account with the following command:
PS C:\> az login
-
Set your active subscription with:
PS C:\> az account set --subscription "<YOUR SUBSCRIPTION NAME>"
-
Create a Service Principal:
PS C:\> az ad sp create-for-rbac -n "<YOUR SERVICE PRINCIPAL NAME>"
-
Note the following appId, password and tenant values:
{ "appId": "<YOUR APP ID>", "displayName": "blahblah", "name": "http://blahblah", "password": "<YOUR PASSWORD>", "tenant": "<YOUR TENANT ID>" }
-
Add an
appsettings.json
file to the directory withProgram.cs
-
Fill in the authentication values from above and key vault settings:
{ "AzureADAuthSettings": { "appId": "<YOUR APP ID>", "password": "<YOUR PASSWORD>", "tenantId": "<YOUR TENANT ID>" }, "KeyVaultSettings": { "keyVaultName": "<YOUR KEY VAULT NAME>", "secretName": "<YOUR KEY VAULT SECRET NAME>" } }
-
Give the application permission to get the secret from your keyvault
PS C:\> az keyvault set-policy --name "<YOUR KEY VAULT NAME>" --spn "<YOUR APP ID>" --secret-permissions get
- Either run
dotnet run
or run within Visual Studio/Visual Studio Code.