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.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.
- Login to the Azure portal
- Go to Azure Active Directory
- Go to App registrations
- Click "New application registration"
- 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)
- Copy the application id to the appsettings.json file as the clientId.
- Click on settings in the newly created application registration.
- Click on Keys
- Enter a name of the key (doesn't matter much), select a duration and hit save.
- 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
- Create a keyvault if you don't have it yet and/or select it in the portal.
- Go to "Access Policies".
- Click on "Add New".
- Under "Select Principal" choose the name of the app registration.
- Select the permissions you want for this app.
- 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
- With the KeyVault selected in the portal, select "Secrets".
- Press Generate/Import
- As the Name type "ConnectionString".
- Enter some value as the secret.
- Leave everything else as it is and press "Create".
- 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.