Secure secrets using Azure KeyVault with examples

Secure secrets using Azure KeyVault MSI in C#.NET

Today in this article, we will see how to Secure secrets using Azure KeyVault with examples. We will see step-by-step detailed examples of how to secure and use secretes using the KeyVault service.

Updated October 2026: an RBAC and Key Vault Secrets User section, a local development and DefaultAzureCredential section, and an FAQ.

Today in this article, we will cover below aspects,

We will see how to use Managed identity for accessing Azure Key vault resources and will also cover how to access Azure key vault resources without using the Managed identity.

We will use Azure portal and Azure CLI commands both ways to achieve the same.

In this tutorial, we will deploy the web application to Azure App Service. We will use the Azure Key Vault secret client library for .NET and the Azure CLI. 

Managed identity let you authenticate to any service inlcuding Key Vault that supports Azure AD authentication.

Also You need not have to store keys or secretes in the code.

You’ll use a managed identity to authenticate your Azure web app with an Azure key vault using

Azure KeyVault service is language agnostics (like any other Azure services offered) and can be used for .NET, JAVA, Node JS, and Python application as required.

Below discussed high-level steps can be followed in any language of your choice.

We will use a simple .NET API which will connect to Azure Vault to get the secured credentials like Connection string etc.

KeyVault lets you securely access secretes and sensitive information from within your applications. These Keys, secrets, and certificates are protected without you having to write the code yourself, and you can easily use them from your applications.

Authentication in Key Vault works using Azure Active Directory (Azure AD) where, Azure AD authenticates the identity of any given security principal.

Before we get started we will perform the basic configuration required for the Azure Key Vault service to function properly.

We will use a simple application that we will be hosting in Azure Cloud. This application will use the Vault to get the sensitive credentials.

Secure secrets using Azure KeyVault – Getting Started

Prerequisites

Before we get started with actual Azure Vault implementation please make sure you have the below prerequisites defined already in your Azure cloud account,

  • Create a Resource group( if not already exist )
  • Create an App Service plan
  • Create Azure WebApp (App Service) in the App service plan

Azure Key Vault Service Setup

We can set up the Azure Key Vault service using multiple approaches.

We will mainly see two approaches i.e using Azure CLI and Azure Portal in this article

Create Azure Key Vault service using Azure Portal

Azure KeyVault with examples

Define configuration of KeyVault

Azure portal Create a key vault form with resource group thecodebuzz-group and key vault name thecodebuzz-vault circled in red

Add Access policy using Managed Identity for Azure KeyVault

Please define the access policy as required for the vault service. Note that Microsoft now recommends the Azure RBAC permission model for new vaults, so see the RBAC section below for the Key Vault Secrets User role equivalent.

Azure KeyVault C# example

  • Above I have defined only “Get” access to key vault service.

  • For the “Select Principal” option, select the Azure Web App that you enabled Identity Management previously.
Principal selection dialog searching for thecodebuzz-app, showing its application ID

Once done your Vault account will be created successfully

Below highlighted URL is your AzureKy Vault URL.

Azure Key Vault overview page for thecodebuzz-key-vault, with its Vault URI underlined in red

Please make a note of Vault URI “https://thecodebuzz-key-vault.vault.azure.net/” this is going to be used on the C# logic to connect to Vault and fetch the secretes. We will see more on the same in the below section.

Add Secretes to KeyVault

Let’s now go to our Key Vault and add application secrete,

Azure KeyVault node js example

Above I have added new secretes called “YourSecreteCode” with a value of “you are beautiful“

Using Azure CLI for adding Managed Identity for the KeyVault service

Alternatively, If interested we can perform the above steps using CLI as well.

One can use the AZ CLI command to create an Azure Key Vault service account as below,

The below command can be used to create an Azure Key Vault account.

Command

az keyvault create --resource-group "thecodebuzz-group" --name "thecodebuzz-vault"

assign-identity command to create the identity for this application

Command

az webapp identity assign --name "<App-Service-Name>" --resource-group "<Resource-Group-Name>"

Example

az webapp identity assign --name "thecodebuzz-web-app-service" --resource-group "thecodebuzz-group" 

Once executed successfully,

You shall see the output below,

{
   "principalId": "4a6bdc47-xxx-4402-xxxx-fc2861108d1c",
   "tenantId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
   "type": "SystemAssigned"
 }

As a next step, please run the below command to set the policy.

  • The web app application is given permission to do get or list operations on your key vault bypassing the principalID obtained above

Command

az keyvault set-policy --name '<key-Vault-Name>' --object-id <principalId> --secret-permissions get

Example

 az keyvault set-policy --name 'thecodebuzz-key-vault' --object-id '4a6bdc47-xxxx-4402-xxxx-fc2861108d1c' secret-permissions get 

Create ASP.NET Core API or MVC application using .NET 6 or .NET 5

Let’s create our sample application here. Our target will be to deploy the application cloud Azure app service associated with App Service Plan.

Secure secrets using Azure KeyVault with examples

Add below two NuGet packages (use the latest stable releases; Azure.Security.KeyVault.Secrets is at 4.11.2 and the 4.12 betas are prerelease),

Install-Package Azure.Security.KeyVault.Secrets -Version 4.3.0

This library allows you to securely store and control access to tokens, passwords, API keys, and other secrets. This library offers operations to create, retrieve, update, delete, purge, backup, restore, and list the secrets and their versions.

and

Install-Package Azure.Identity -Version 1.6.0

This library provides Azure Active Directory token authentication support.

Please add below using namespaces,

using Azure.Identity;

using Azure.Security.KeyVault.Secrets;

You can use the same logic as it is Console/API or other type of Application as well

Open your project solution in Visual Studio. Go to Program.cs and add the below-highlighted code

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, config) =>
            {
                var settings = config.Build();

                if (!context.HostingEnvironment.IsDevelopment())
                {
                    var keyVaultEndpoint = settings["VaultURI"];
                    if (!string.IsNullOrEmpty(keyVaultEndpoint))
                    {
                        var azureServiceTokenProvider = new AzureServiceTokenProvider();
                        var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
                        config.AddAzureKeyVault(keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
                    }
                }

            }).ConfigureWebHostDefaults(webBuilder =>
               {
                   webBuilder.UseStartup<Startup>();
               });
    }

That’s all. Now Azure Key Vault credentials will become part of your IConfiguration root object along with all available configurations.

The above steps will help you manage the azure credentials just like any other configuration and hence let you handle updates or edits to key vault secrets based on how you set your configuration in the API or Application pipeline.

For Accessing Azure Key Vault credentials you need to inject the IConfiguration interface in the required module of your choice.

Example

 public IActionResult Index()
        {

            string keyVaultUrl = _configuration["YourSecreteCode"];

            return Ok("Your Secrete is -" + keyVaultUrl);
        }
Secure secrets using Azure KeyVault C#.NET

Similarly, if you hit the WebApp endpoint,

Browser showing the web app page displaying the text 'Your Secrete is -you are beautiful !'

If you are interested to know non-msi approach by using enviornment variable setup , please visit below article- Secure secrets using Azure KeyVault -Approach II

Other references :

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published (2026) best practices and guidelines for software design and development.



Frequently asked questions

What is the difference between a system-assigned and a user-assigned managed identity for Key Vault?

A system-assigned identity is created with the app and deleted with it. A user-assigned identity is a separate resource that you can create and grant vault access to in advance, and share across apps. That helps when an App Service must reference secrets at creation time, before a system-assigned identity exists.

For Key Vault references, App Service uses the system-assigned identity by default. Set the keyVaultReferenceIdentity property to the user-assigned identity’s resource ID to switch. The setting applies to all Key Vault references in the app, so you can’t mix identities per reference.

How do Key Vault references in App Service app settings work?

An app setting value can point to a Key Vault secret, and App Service resolves it using the app’s managed identity. Your code reads it like a normal setting or environment variable, with no SDK call. This is an alternative to the SecretClient and configuration provider approach used in this article.

The identity needs the Get secrets permission on access policy vaults, or Key Vault Secrets User on RBAC vaults. The vault’s network settings must also allow the app’s network or subnet, or the reference won’t resolve.

Why do I get 403 Forbidden or “does not have secrets get permission” from Key Vault?

The identity is authenticating, but the vault isn’t authorizing it. Check these in order:

  1. Identity enabled: confirm the managed identity is turned on for the app.
  2. Permission model: make sure the vault’s model (RBAC or access policy) matches how you granted access. An access policy on an RBAC vault is ignored.
  3. RBAC role and scope: on RBAC vaults, the identity needs Key Vault Secrets User at a scope that covers the secret.
  4. Access policy permissions: on access policy vaults, the identity needs Get, plus List if the caller lists secrets.
  5. Firewall: check that the vault firewall allows the app’s network.
  6. Propagation time: wait a few minutes after a role assignment, because RBAC changes can take a little while to apply.

How do I read a Key Vault secret locally without storing credentials?

Use DefaultAzureCredential with SecretClient. Sign in with the Azure CLI or Visual Studio using an account that has read access to the secret.

The same code then uses the managed identity once deployed to Azure. No connection strings or client secrets end up in your source or config.

Leave a Reply

Your email address will not be published. Required fields are marked *