Azure Key Vault Implementation

Continuing to the previous blogs where we learned about Azure Key Vault Overview and also about Key Vault Lifecycle, lets do some hands on and understand how Key Vault is implemented in real world scenario.

Today we will cover how to Authenticate a Client Application with Azure Key Vault using Azure Active Directory Application and how to set various access policies for the applications. Each application should be given minimum set of permissions that it requires to operate on. A Security Administrator would be given full permission so that it could modify the Vault Key/Secret as required and an Azure Developer will have limited permissions on Keys and Secrets. For Such a scenarios, it is best to have two or more AD applications created and have separate permissions provided.

Azure Key Vault Implementation

Process flow:
1) The application first uses the AD application credentials to authenticate and once obtained the Access Token is used for further interactions with the Key Vault. Using the Key Identifier that is available we get the details of the key. We have to provide the appropriate permissions by Set-AzureKeyVaultAccessPolicy, against the key vault. In C# we generally Encrypt data with the System.Security.Cryptography.RSA algorithm.

To implement Azure Key Vault to our applications we have 4 Steps:

  • Create an Azure AD Application
  • Creating Key Vault and associate the Service Principal
  • Create a Key and Secret in Key Vault
  • Using Key Vault from a Web Application

Step 1: Create an Azure AD Application

We have to create an AD Application that will authenticate using Client ID and Client Secret, generating the credentials can be done using either Powershell or Azure Portal.

In this Step we cover Powershell way to create an Azure AD Application

Pre-Requisites:

  • Powershell with Azure Module Installed.
  • Required Permissions needed to create an AD Application.
  • Azure Portal Access.

Procedure:

  • Run the below powershell code to create an Azure AD Application. When the script starts running a pop-up appears where we have to specify the username and password for Azure Account. Once its authentication then an AD Application is created.
#Login to Azure Module from powershell.
Login-AzureRmAccount

$aadClientSecret = 'ramClientSecret'
$appDisplayName = 'ramKvApp'

#To Create an AD Applicatication with a custom Password
$aadApp = New-AzureRmADApplication -DisplayName $appDisplayName -HomePage 'http://ramKvApp' -IdentifierUris 'http://ramKvApp' -Password $aadClientSecret

$appID = $aadApp.ApplicationId

#Creating a Service Principal to the Application
$aadServicePrincipal = New-AzureRmADServicePrincipal -ApplicationId $appID
  • Once the script completes running successfully we can navigate to Azure Portal and Search for App Registrations and select. Navigate to App Registrations

  • Search by AD Application Name and note the Application ID which is our Client ID and the Client Secret from the above Script(in our case its 'ramClientSecret').

Step 2: Creating Key Vault and associate the Service Principal

Pre-Requisites:

  • Powershell with Azure Module Installed.
  • Required Permissions needed to create an AD Application.
  • Azure Portal Access.

Procedure:

  • Run the below powershell script to create a Resource Group in an Azure Subscription. In the above step as we have logged in to Azure Subscription, we create a Resource Group to place Key Vault resource inside it.
$kvName = 'ramKV'
$rgName = 'ramRG'
$location = 'South India'

#selecting target Subscription
Select-AzureRmSubscription –SubscriptionName ‘<SubscriptionName>’

#creating a Resource Group from the above values
New-AzureRmResourceGroup -Name $rgName -Location $location  
#creating an Azure Key Vault from the above values.
New-AzureRmKeyVault -VaultName $kvName -ResourceGroupName $rgName -Location $location

#assigning the Access policy to the Key Vault
Set-AzureRmKeyVaultAccessPolicy -VaultName $kvName -ServicePrincipalName $appID -PermissionsToKeys all –PermissionsToSecrets all  
  • In the above script we create a resource group and also assign an access policy to the target key vault.
  • Once the script run successfully we can navigate to Azure Portal and search for the Resource Group and click on Key Vault.

Azure Key Vault in a Resource Group

Step 3: Creating and Deleting Key and Secret in Azure Key Vault

As we have created AD Application and Key Vault let now create Key and Secret in Key Vault(for more info on Keys and Secret)

It walks you through the process of accessing a secret from an Azure Key Vault so that it can be used in your web

  • Adding a Key or Secret to Vault:
#creating a Software protected Key
$key = Add-AzureKeyVaultKey -VaultName ‘ramKeyVault' -Name 'softProtectKey' -Destination 'Software'
  • If we have an existing software-protected key in a .pfx file saved at local machine named “KeyCert.pfx” that can be uploaded to Azure Key Vault:
# .pfx certificate password
$securepfxpwd = ConvertTo-SecureString –String 'Password@123' –AsPlainText –Force

#import the key from the .PFX file, which protects the key by software in the Key Vault service
$key = Add-AzureKeyVaultKey -VaultName 'ramKeyVault' -Name 'CertificateKey' -KeyFilePath 'C:\keyCert.pfx' -KeyFilePassword $securepfxpwd
  • To add a secret say SQL Password which is sqlpassword to the Key Vault, firstly we convert it to SecureString by typing the following:
#convert password to Secure String 
$secretvalue = ConvertTo-SecureString 'sqlpassword' -AsPlainText –Force

#assigning a Secret to Key Vault
$secret = Set-AzureKeyVaultSecret -VaultName 'ramKeyVault' -Name 'SQLPassword' -SecretValue $secretvalue
  • To display the URL of the Secret, the below URL is also called as Key Identifier which can be found from Azure Portal as well:
#which will be similar to https://ramkv.vault.azure.net/secrets/demFinals/f2b508e89d3f44b6a184f97dd967e51d
$secret.Id
  • To get all available Keys & Secrets in the Key Vault:
#List of keys in the Key vault named 'ramKeyVault'
Get-AzureKeyVaultKey –VaultName 'ramKeyVault'

#List of Secrets in the Key vault named 'ramKeyVault'
Get-AzureKeyVaultSecret –VaultName 'ramKeyVault'  
  • Delete the Key Vault and associate keys and Secrets:
#remove Azure Key Vault from the subscription 
Remove-AzureRmKeyVault -VaultName 'ramKeyVault'  

Link for More Powershell Key Vault Modules: https://docs.microsoft.com/en-us/powershell/resourcemanager/azurerm.keyvault/v2.1.0/azurerm.keyvault?redirectedfrom=msdn

Step 4: Using Key Vault Secret from Web Application

Pre-requisites:

  • A URI to a secret in an Azure Key Vault
  • A Client ID and a Client Secret for a web application registered with Azure Active Directory that has access to your Key Vault
  • An ASP.NET MVC application deployed in Azure as a Web App/Virtual Machine

Procedure:

  • There are two packages that your web application needs to have installed. Both of these packages can be installed using the Package Manager Console using the Install-Package command.

Add Nuget Packages:

// this is currently the latest stable version of ADAL
C:\> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.16.204221202  
C:\> Install-Package Microsoft.Azure.KeyVault  

adding Nuget Packages

  • Modify Web.Config add Web.Config

  • Add a Method to get an Access token.

//add these using statements
using Microsoft.IdentityModel.Clients.ActiveDirectory;  
using System.Threading.Tasks;  
using System.Web.Configuration;

public static string EncryptSecret { get; set; }

public static async Task<string> GetToken(string authority, string resource, string scope)  
{
    var authContext = new AuthenticationContext(authority);
    ClientCredential clientCred = new ClientCredential(WebConfigurationManager.AppSettings["ClientId"],
                WebConfigurationManager.AppSettings["ClientSecret"]);
    AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);

    if (result == null)
        throw new InvalidOperationException("Failed to obtain the JWT token");

    return result.AccessToken;
}
  • Retrieve the secret on Application Start Now we need to get the secret from Azure Key Vault by calling the Key Vault API and retrieve the secret. We can place the below code at application start (in our case its Global.asax).
using Microsoft.Azure.KeyVault;  
using System.Web.Configuration;

// I put my GetToken method in a Utils class. Change for wherever you placed your method.
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(Utils.GetToken));

var sec = kv.GetSecretAsync(WebConfigurationManager.AppSettings["SecretUri"]).Result.Value;

//I put a variable in a Utils class to hold the secret for general application use.
Utils.EncryptSecret = sec;

ASP.NET Application with key Vault

  • Run the application which will fetch the Connection String Secret from Azure Key Vault and pass the Key Vault Secret (ConnectionString) at runtime to the application

Summary

From the above blog we can learn how Azure Key Vault can be used to store Application Secrets(API Keys/Connection Strings, etc) and how we can retrieve the secret from Key Vault.

Privacy and encryption works, but it's too easy to make a mistake that exposes you. So let's leverage Key Management System and stay safe with your application secrets.

Thanks for reading and keep learning :)

Raghuram Korukonda

Most of my time I spent working on Azure and contributing to Microsoft Azure and other Open Source Communities. I am passionate about Technology and helping people in embracing it to the fullest.

Hyderabad, India

Subscribe to Cloud Blog

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!