[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()
        {
            Test();
            return View();
        }

        public async void Test()
        {
            var keyVaultClient = new KeyVaultClient(AuthenticateVault);
            var result = await keyVaultClient.GetSecretAsync(“
https://duracellkeyvault.vault.azure.net/secrets/DBConnectionString/e294bxxxxxx1de1efce672f”);
            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:-

1

2) Add application under AAD

2.1

2

3

4

5

6

7

8

Azure Key Vault Explorer:-

9

References:-

https://github.com/elize1979/AzureKeyVaultExplorer/blob/master/README.md 

https://docs.microsoft.com/en-us/azure/key-vault/key-vault-use-from-web-application#a-idappstartaretrieve-the-secret-on-application-start

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

Comments (0)

Skip to main content