Contains an example integration of Azure Key Vault in a .NET (Framework) project.
- Active Azure subscription
- Tip: You could have an MSDN Azure subscription with free credits via your workplace.
- Azure Key Vault
- .NET Framework 4.8
In HomeController I've added code to retrieve a secret from the Azure Key Vault:
var client = new SecretClient(new Uri(ConfigurationManager.AppSettings["Azure.KeyVaultUri"]), new DefaultAzureCredential());
var secret = await client.GetSecretAsync("mysupersecretsecret");
The example(s) can be found in the samples
directory.
- Create a secret in your Azure Key Vault. The code in this project expects a secret with the name
mysupersecretsecret
. You can use your own secret name, but make sure to change the code accordingly if doing so. - You can run the web app locally (on-premise) or in an Azure Web App. Follow the steps of your choice.
We need to create an app registration and we'll grant it access to the Key Vault. Then we need to configure Key Vault credentials in the local environment.
- Create an Azure Active Directory (any pricing model will do)
- Create an App Registration in the Active Directory
- Create a secret for your App Registration (in left-side menu in the Azure Portal) and save it somewhere
- Note the Client ID and Tenant ID of your App Registration somewhere alongside the secret.
- Create an access policy. Make sure to select the app registration as principle and grant it the
Secret Management
permissions template. If you don't want to use a template, make sure to grant the principal a Get secret permission. - Now that everything in Azure is configured, all that remains is the local environment. Add 3 user environment variables:
- AZURE_CLIENT_ID (Client ID from App Registration)
- AZURE_TENANT_ID (Tenant ID from App Registration)
- AZURE_CLIENT_SECRET (Secret you created in the app registration)
- Run the website. You should see your secret on the homepage.
- Create an Azure Active Directory (any pricing model will do)
- Create an Azure Web App (any pricing tier will do)
- Add a system-assigned identity for the Web App.
- Create an access policy. Make sure to select the system-assigned identity as principle (usually the Web App name) and grant it the
Secret Management
permissions template. If you don't want to use a template, make sure to grant the principal a Get secret permission. - Deploy the website to the Azure Web App.
- Go the the URL of your Web App and you should see your secret value.