In past few articles, I have tried to explain how key vaults can be created and can be accessed from .NET core web application.
Plan of Action
We are going to create a console application that performs create, update, delete, purge operations on key vault. This console application will use the service principal, which will be created using Azure CLI.
So, below are the steps which we are going to perform:
- Create key vault
- Create service principal using CLI
- Add access policy in key vault
- C# Code to perform create, update, delete, purge operations
I have created Azure CLI script for first three operations. So there will be a section to cover it. The C# code is covered in the subsequent section of this article.
So, let’s get started !
Azure CLI Script
Below is the Azure CLI script to create the key vault and create the service principal. Then the script also configures the access policy on key vault and provides all the access rights to the service principal.
If you want to use Azure Portal for preforming above steps, refer my blog posts mentioned below:
- Creating your first Azure key vault instance, for creating key vault using Azure Portal
- Service principal and client secret with Azure key vault – for understanding how to add key vault access policy using Azure Portal
Note for curious minds…
If you go to App registrations -> All applications tab from the Azure AD, it would show the application with app-name (which we have provided in the command).
Create a .NET Core console application using Visual Studio 2019.
Then add reference to below NuGet packages:
There are three important classes which we are going to use:
- KeyClient – provides both synchronous and async APIs, that can be used to interact with key vault
- Cryptography Client – provides both synchronous and async APIs, to perform cryptographic operations with keys stored in Key Vault.
- KeyVaultKey – represents keys from the key vault, representing the value of key and some other properties
- ClientSecretCredential – is the class from Azure.Identity package which takes tenant id, client id and client secret of the service principal which is helped for app authentication.
Below is the sample code which shows some basic operations performed on keys stored in key vault.
The sample snippet also tries to use the keys in key vault and shows how they can be used for encryption and decryption using Cryptography client.
If you run the console application, you would be able to view the keys in key vault (if they are not deleted / purged yet).
I hope you enjoyed this article. Let me know your thoughts.