Introduction

In this blog, we will see how to get secret from the Azure Key Vault in Azure Function.

Prerequisites

  1. Access to Azure account (Admin)
  2. Visual Studio 2017

What’s New in Azure Function

Earlier, we had to manually register Application under Azure Active Directory to get Client Id(Application Id) and Client Key(Client Secret).

But this approach has a drawback

  1. Manually check when client key is going to expired
  2. Hard-code client key in app setting/configuration page.

With a new enhancement, Azure will take care of Application Registration and keep client key secret from the user.

Advantage

  1. Azure will automatically add Application under Active directory and create a principal user for Azure Function.
  2. No need of Client Id and Client Secret Key to retrieve the value from Key Vault.

Steps

  1. Create a Resource Group
  2. Create a new Azure Function App
    • Provision the service
    • Enable Identity(System Assigned) under Platform features
  3. Create a new Key Vault
    • Provision the service
    • Add secret Key-Value
    • Add Policy for Azure Function
  4. Deploy the Azure Function using Visual Studio
    1. click here to view the code
  5. Validate using Postman(REST Call)

Steps in Detailed

1. Create a Resource Group

  1. Navigate to Azure account
  2. Click on + sign
  3. Enter the name and select the appropriate location
Go to Resource Group

2. Create a new Azure Function App

Add new resource under resource group
Search for the Function App
Enter required information and create a function app
Select platform features
Accept the permission

3. Create a new Azure Key Vault

Select standard pricing tier
Add a new policy for Azure Function
Select the Function App

4. Deploy the Azure function from Visual Studio

Click here to follow the prerequisites for Azure function

  1. Open the visual studio and create a new Project as a Azure Function App

Install following Packages from NuGet Package manager

  1. Microsoft.Azure.Services.AppAuthentication
  2. Microsoft.Azure.KeyVault
Install
Microsoft.Azure.Services.AppAuthentication package from NuGet

From the Portal Copy Key Vault URL.

Click here to download code from GitHub

Publish this App to Azure
Please wait for the Operation

Open the Azure Portal and Navigate to Azure Function App

Using Postman sent request to Azure Function . Do not forget to add name attribute from as Key

Yippee !!! Finally we have retrieved the value from the key vault .

Tips

You can perform similar steps for other Azure services to get value from the Azure Key Vault. Just find Identity tab and make required modifications.
Cheers !!!!!

Help Links

https://docs.microsoft.com/en-us/azure/azure-functions/

https://docs.microsoft.com/en-us/azure/key-vault/key-vault-whatis

https://dzone.com/articles/using-msi-with-azure-functions-and-key-vault