Peritos Solutions
Published in

Peritos Solutions

Using Azure Key Vault

Azure Key Vault is the Azure service to help safeguard and manage cryptographic keys and secrets used by cloud applications and services. Azure Key Vault provides functionality to securely store the data by providing one of the most secure data storage in the cloud.

Key Vault provides 3 different kinds of storage options i.e. secrets, keys and certificates along with an option to store these values in Hardware security modules, thus providing utmost security for your data.

This article focus on using Key Vault Secret specifically to store the configuration settings securely and different ways to access those settings. Although Key vault doesn’t restrict you to store any specific data in Key Vault secrets, it can store any kind of data in key-value pair where value can also be a JSON object.

Below scenarios are covered in this article:

Different ways of Using Key Vault

Azure Key Vault provides different kinds of controls over accessing the values stored in the Key Vault Secrets. You can give read/write/delete access to specific users from the directory and/or to registered applications.

Accessing the Key Vault using AD registered application

This is probably the easiest way to use Azure Key Vault where secrets can be directly accessed using the secret’s endpoint. For this approach, you would need to register an application in the Azure AD and give it Key Vault API access. Below is the code to read KeyVault secret values:

async Task<string> GetToken(string authority, string resource, string scope)
{
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(ClientId, ClientSecret);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
throw new InvalidOperationException("Failed to obtain the JWT token");
return result.AccessToken;
}
string GetValueWithClientIdSecret(string key)
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
var secretBundle = keyVaultClient.GetSecretAsync(VaultBaseUrl, key).ConfigureAwait(false).GetAwaiter().GetResult();
return secretBundle.Value;
}

The problem with this approach is Key Vault access is also stored in plain text in Azure AppSettings thus providing keys to access all the secrets. This problem is called the bootstrapping problem. It’s more like putting all the secrets in the vault and store the key of the vault in open. This approach defeats the purpose of using Key Vault as the secrets are not really safe.

Another problem is that a new secret endpoint is created for every version of the secret. So if you update the secret’s value a new endpoint is created to access the new version, thus the value is required to be read from the new endpoint.

Using Managed service identity to access Key Vault

Using AzureAD registered app creates a problem of storing the Client Id and Secret, and since these values are required to access the Key Vault it cannot be stored in Key Vault. The feature of ‘Managed service identity’ can resolve this problem where service/application which requires to access the key vault is directly assigned the access, thus removing the step of registering the application in Azure AD. When you enable managed identity on your web app, Azure activates a separate token-granting REST service specifically for use by your app. Your app will request tokens from this service instead of Azure Active Directory. Below is the command to enable managed identity on the app

az webapp identity assign \
--resource-group <resource-group-name> \
--name <your-app-name>

For local development, developers can be assigned access to the Secret management and when they run the application on their machines, access is checked against their Azure account.

Users can check the access to Key Vault using below Azure CLI command:

az keyvault list

Please note, Managed service identities is not currently supported for Linux or Container web apps.

For further details on managing Azure Key Vault please refer this link.

Reading configuration using keys (More suitable for .Net Core application)

.Net core supports adding Azure Key Vault in the configuration builder, thus providing an option to use KeyVault directly for reading the configuration. Coupled with ‘Managed service identity’, this solution provides the best security features as well as easily maintainable configuration. Users with proper rights can directly go into Azure Key Vault and add/update the secrets by using manageable key names. Below is a code abstract which can be used for reading configuration from Azure Key Vault

/// <summary>
/// Configuration Builder we are targeting
/// </summary>
private readonly IConfigurationRoot _configuration;

/// <summary>
/// Initializes a new instance of the <see cref="ConfigurationBase"/> class.
/// </summary>
protected ConfigurationBase()
{
var builder = new ConfigurationBuilder();
this._configuration = builder.Build();
var keyVaultEndpoint = $"https://[keyvaultname].vault.azure.net/";
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));
builder.AddAzureKeyVault(keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
this._configuration = builder.Build();
}

// <summary>
/// Gets the setting.
/// </summary>
/// <param name="settingName">Name of the setting.</param>
string GetSetting(string settingName)
{
return this._configuration.GetSection(settingName).Value;
}

This code can also be extended to ApplicationSettings as a fallback so that any non-critical configuration can still be stored in AppSettings (i.e. if the key is not found in KeyVault it will read from AppSettings):

/// <summary>
/// Configuration Builder we are targeting
/// </summary>
private readonly IConfigurationRoot _configuration;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigurationBase"/> class.
/// </summary>
/// <param name="keyPrefix">Name of the system configuration we are working with</param>
protected ConfigurationBase()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
this._configuration = builder.Build();
var secureSettings = Convert.ToBoolean(this._configuration["\SecureConfig"]);
if (secureSettings)
{
var keyVaultEndpoint = $"https://{_configuration["KeyVault:Vault"]}.vault.azure.net/";
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));
builder.AddAzureKeyVault(keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
this._configuration = builder.Build();
}
}
/// <summary>
/// Gets the setting.
/// </summary>
/// <param name="settingName">Name of the setting.</param>
/// <returns>the requested setting.</returns>
protected string GetSetting(string settingName)
{
return Environment.GetEnvironmentVariable($"APPSETTING_{settingName}") ??
this._configuration.GetSection(key).Value;
}

In order to create below structure in Key Vault secret i.e. to read DBConfig.ConnectionString, the name of the secret should contain ‘--’ e.g. DBConfig--ConnectionString

{
"DBConfig": {
"ConnectionString": "<<ConnectionString>>"
}
},

Using Key Vault references for Application Settings

Microsoft recently announced a new feature of Key Vault references for Application settings. This is currently in Public Preview. This feature allows your existing application to use Key Vault for accessing application settings without changing any code. The application gets authorized using ‘Managed service identity’ to access Key Vault. You just have to update the Application Settings of the application to read the value from Secrets using

@Microsoft.KeyVault(SecretURI=’’) or @Microsoft.KeyVault(VaultName=’’,SecretName=’’,SecretVersion=’’) .

We hope you are able to use Azure Key Vault and manage and improve security on your application configuration more easily.

Please leave us a comment and give us a clap if you liked our blog and visit our website if you have any specific questions for us. Visit our service page here

Contact us using the link below

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Peritos Solutions

Startup firm that believes in breaking technology barriers and helping small to medium businesses to grow. Use IT as a powerful means to solve business problems