[AzureKeyVault] How to retrieve Keyvault secrets using C# code

Azure Key Vault needs no introduction, it’s already adapted by Azure developers to safeguard keys and secrets used by cloud applications and services.

– it used to encrypt keys and secrets (such as authentication keys, storage account keys, data encryption keys, .PFX files, and passwords) by using keys that are protected by hardware security modules (HSMs). –> Keys and secrets are protected without having to write the code yourself and you are easily able to use them from your applications. Developers now can focus on developing application rather writing framework to protect the secrets in their application. Recently I had a chance to read about this topic, so putting here in steps to follow. Assuming you have a KeyVault created in Azure having secrets say connectionstring, so as a developer I have only GET permission to the vault.

Some prerequisites.

1) Create a vault, store the secrets –> URI to a secret in an Azure Key Vault

2) Client ID and a Client Secret for a web application registered with Azure Active Directory that has access to our Key Vault

3) ASP.NET MVC application to have the below code.

sample code:-

public class HomeController : Controller

        public async Task<ActionResult> Contact()
            return View();

        public async void Test()
            var keyVaultClient = new KeyVaultClient(AuthenticateVault);
            var result = await keyVaultClient.GetSecretAsync(“
            var connectionString = result.Value;

        private async Task<string> AuthenticateVault(string authority, string resource, string scope)
            var clientCredentials = new ClientCredential(“d75a9f8b-xxxxxxx”, “4QupfP1Bq5KekdXuEJuQoUxxxxxxxxxkhuUOpGWE=”);
            var authenticationContext = new AuthenticationContext(authority);
            var result = await authenticationContext.AcquireTokenAsync(resource, clientCredentials);
            return result.AccessToken;

Create the secrets:-


2) Add application under AAD









Azure Key Vault Explorer:-





Introduction to Microsoft Azure Key Vaulthttps://www.youtube.com/watch?v=5p2dQdTsUvE (Azure Key Vault by the Program Manager)

Comments (3)

  1. rosdi says:

    Nice.. tq

  2. Brunas says:

    Thanks for really nice example.
    However, I struggled a bit to find the Client Secret to be used together with Client ID. This should be described better in this post. This is a key created in Keys tab of registered application properties.

    1. Hi Brunas, Client secret and ID harvesting may go into AAD side and there are many articles around that.
      That’s the reason, I did not go in detail. but anyway, thanks for the feedback. Let me see how to add that detail here.

Skip to main content