Creating Azure Key Vault for programmatic access

...
  • By Ivan Gavryliuk
  • In Microsoft Azure  |  Azure Key Vault
  • Posted 01/08/2017

Azure Key Vault is a wonderful technology I've just discovered. I'm only looking at secrets as of now as this is something I was interested in for a few reasons. One of my current problems in cloud world is storing configuration. In .NET we would usually deploy some form of app.config file within the application and update it every time a value changed. I find it sucks a lot as I need to write deployment scripts putting a proper file with each deployment, hiding "production only" settings or replacing them with certain values on start etc.

Key Vault is sort of a central repository for configuration. Generally Key Vault consists of Keys and Secrets. Keys are designed mostly for on demand encryption and Secrets are sort of key-value pairs with cool features on top of them. But most importantly, Key Vault has a management console in the Portal which allows you to change secret values, see the history of changes, audit changes, revoke them etc., and all for cheap.

The docs on Key Vault are pretty self-explanatory, so I'll only add a few bits. I've managed to fully automate Key Vault creation with PowerShell, including granting access with Active Directory service principal:

$appName = "PluralDemo02"
$region = "ukwest"

#generate a random password
Add-Type -AssemblyName System.Web
$password = [System.Web.Security.Membership]::GeneratePassword(10, 2)

# Create a new Key Vault
$rg = New-AzureRmResourceGroup -Name $appName -Location $region
$vault = New-AzureRmKeyVault -ResourceGroupName $appName -Location $region -VaultName $appName
 
# Create a new Active Directory Application with Password authentication. Consider a stronger auth for production such as certificate or key.
$app = New-AzureRmADApplication -DisplayName $appName -HomePage "https://localhost/$appName" -IdentifierUris "https://localhost/$appName" -Password $password
New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId

# Associate Key Vault with Azure AD application
Set-AzureRmKeyVaultAccessPolicy -VaultName $appName -ServicePrincipalName $app.ApplicationId -PermissionsToSecrets all

# Give access to outselves so we can add the secret from the script
Set-AzureRmKeyVaultAccessPolicy -VaultName $appName -UserPrincipalName "your_login" -PermissionsToSecrets set

# Create test secret to access from C# code
$secretValue = ConvertTo-SecureString "the secret for Pluralsight" -AsPlainText -Force
$secret = Set-AzureKeyVaultSecret -VaultName $vault.VaultName -Name "FirstSecret" -SecretValue $secretValue

$vaultUri = $vault.VaultUri
$clientId = $app.ApplicationId.Guid

Write-Output "Please write down these values:"
Write-Output "------------------------------"
Write-Output "vault uri: $vaultUri"
Write-Output "client id: $clientId"
Write-Output "password: $password"

And here is a sample code to read the created secret:

using System;
using System.Threading.Tasks;
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace VaultDemo
{
   class Program
   {
      private const string VaultUri = "your_vault_uri";
      private static readonly ClientCredential Credential = new ClientCredential(
         "client_id", "password");

      private static KeyVaultClient _client;

      static void Main(string[] args)
      {
         _client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken));

         Console.WriteLine("reading FirstSecret...");
         Secret secret = _client.GetSecretAsync(VaultUri, "FirstSecret").Result;

         string value = secret.Value;

         Console.WriteLine("value is: " + value);
         Console.ReadLine();
      }

      public static async Task<string> GetAccessToken(string authority, string resource, string scope)
      {
         var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
         var result = await context.AcquireTokenAsync(resource, Credential);

         return result.AccessToken;
      }
   }
}

In the next posts I'll explain how to access key vault in an extremely easy way.


Thanks for reading. If you would like to follow up with future posts please subscribe to my rss feed and/or follow me on twitter.