Retrieving a Secret from Azure KeyVault: Easiest Example Ever

The internet is full of code examples that try to show all possible features of Azure KeyVault. I felt the need for a very basic example just retrieving a secret.

Here it is.

It's an ASP.NET Core console application with a couple of added NuGet packages:

  • Microsoft.IdentityModel.Client.ActiveDirectory (for access token retrieval from Azure Active Directory (AAD)
  • Microsoft.Azure.KeyVault
  • Microsoft.Extensions.Configuration (to access the appsettings.json file with needed settings)

Setup steps in Azure:

Authentication in Key Vault works via Azure Active Directory (AAD). We first have to set that up.


AAD steps

  1. Login to the Azure portal
  2. Go to Azure Active Directory
  3. Go to App registrations
  4. Click "New application registration"
  5. Select a name for the app and fill in some Sign-on URL. A sign-on URL is not important for our purpose. (It is when the app is also doing user authentication with AAD)
  6. Copy the application id to the appsettings.json file as the clientId.
  7. Click on settings in the newly created application registration.
  8. Click on Keys
  9. Enter a name of the key (doesn't matter much), select a duration and hit save.
  10. The key will only be visible at this moment, not when you return later to this page. Copy the key to the clientSecret entry in appSettings.json.

Finally we have to associate our key vault with our created app registration.

KeyVault auth steps

  1. Create a keyvault if you don't have it yet and/or select it in the portal.
  2. Go to "Access Policies".
  3. Click on "Add New".
  4. Under "Select Principal" choose the name of the app registration.
  5. Select the permissions you want for this app.
  6. Hit OK

In the sample app I'm getting the secret with the key "ConnectionString". You have to add that secret as well.

KeyVault steps to add secret

  1. With the KeyVault selected in the portal, select "Secrets".
  2. Press Generate/Import
  3. As the Name type "ConnectionString".
  4. Enter some value as the secret.
  5. Leave everything else as it is and press "Create".
  6. Now copy over the version of the secret to the line of code that gets the secret. You can also omit the version parameter alltogether to just get the latest version of the secret.

When you run the sample now you should see the secret on screen.

Happy vaulting!

Security KeyVault
Tweet Post Share Update Email RSS