Using azure key vault secret in your application

In this post we will see how to use a secret from azure key vault in your web application.To know how to add a secret to azure key vault refer this post.

 

Prerequisites

  • An MVC web application integrated with azure active directory authentication.Refer this post for more.
  • URI of one or more secret(s) added in azure key vault.

 

Nuget packages

To get started we need to have following nuget packages installed.

ScreenClipScreenClip

 

Get the secret from key vault

Now lets try to access the connection string stored in key vault in our application using libraries installed through nuget package. I am not going to show actual usage of connection string but just how to access it .You can use it whichever way you like.

First we need to create a new instance of KeyVaultClient class which takes AuthenticationCallback delegate which essentially is the method which will be called by key vault to get the azure AD access token to see if you are authenticated to access the client secret. So this callback method should have your logic to get the access token using client id and client secret (which are added as part of web.config file).

 

1. Add client id,client secret and Secret Uri(obtained when you add secret to key vault) to web.config.

ScreenClip

2. Add below code to fetch the access token for Azure AD

public static class TokenHelper
{
public static async Task<string> GetAccessTokenAsync(string authority, string resource, string scope)
{
var context = new AuthenticationContext(authority);
ClientCredential credential = new ClientCredential(WebConfigurationManager.AppSettings["ClientId"],
WebConfigurationManager.AppSettings["ClientSecret"]);
AuthenticationResult result = await context.AcquireTokenAsync(resource, credential);
Trace.WriteLine(result.AccessToken);
if (result == null)
throw new InvalidOperationException("Failed to obtain the JWT token");

return result.AccessToken;
}
}

 

3. Add below code to fetch the value of secret from key vault.

var client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(TokenHelper.GetAccessTokenAsync));
var connectionstring = client.GetSecretAsync(WebConfigurationManager.AppSettings["ConnectionStringUri"])
// Logs the value of connection string.Please don’t do this in actual code!!!
Trace.WriteLine(connectionstring.Result.Value);src="https://codingcanvas.com/wp-content/uploads/2017/10/wlEmoticon-smile.png" alt="Smile" />

NOTE : Make sure you have provided correct access permissions for your secrets to your web application.You can check this in Key Vaule > Access Policies –> Click on your application and check the ‘Secret Permissions’ dropdownlist. If not you would keep getting ‘Access Denied’ error.

This is how you fetch the value of secrets from Key vault. For the purpose of this post I am adding the client secret in web.config which kind of defeats the purpose of keeping all secrets and keys in key vault.In a production like scenario you should even add this client secret to key vault.

For further learning , here is an excellent pluralsight course covering design and implementation related cloud  patterns and for in-depth coverage of azure key vault another course specific to key vault.

Tagged on: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.