Overview:
Azure key vault provides a store where you can manage all your keys and secrets effectively. So now, what is the difference between keys
and secrets? It’s simple concept – keys are referring to terms like your encryption keys, however secrets can be any sensitive data like your SQL database connection string or storage access credentials etc.
Azure key vault service is backed by HSM i.e. hardware security modules using certain state of the art algorithms. In simple words – HSM is a mechanism which is used to manage and store these cryptographic keys securely.
Let’s setup Azure KeyVault:
Install NuGet package :
1.Microsoft.Azure.KeyVault
2.Microsoft.IdentityModel.Clients.ActiveDirectory
Add keys in web configuration files:
Get value from vault:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public string GetVaultValue() { KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken)); var vaultAddress = WebConfigurationManager.AppSettings["VaultUrl"]; var secretName = WebConfigurationManager.AppSettings["SecretName"]; var secret = keyVaultClient.GetSecretAsync(vaultAddress, secretName).GetAwaiter().GetResult(); return secret.Value; } public static async Task<string> GetAccessToken(string authority, string resource, string scope) { var clientId = System.Web.Configuration.WebConfigurationManager.AppSettings["AuthClientId"]; var clientSecret = WebConfigurationManager.AppSettings["AuthClientSecret"]; ClientCredential clientCredential = new ClientCredential(clientId, clientSecret); var context = new AuthenticationContext(authority, TokenCache.DefaultShared); var result = await context.AcquireTokenAsync(resource, clientCredential); return result.AccessToken; } |
Set Value of Vault:
1 2 3 4 5 |
public void SetAzureKeyVault(string newValue) { KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken)); keyVaultClient.SetSecretAsync(ConfigurationManager.AppSettings.Get("VaultUrl").ToString(), ConfigurationManager.AppSettings.Get("SecretName").ToString(), newValue); } |