Easily Read Key Vault Secrets From ASP.NET Core Web API Application

Introduction

Azure Key Vault is a tool for securely storing and accessing secrets. A secret is anything that you want to tightly control access to, such as API keys, passwords, or certificates. A vault is a logical group of secrets.

You can refer to the below Microsoft document for more details.

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

Prerequisites

  • Azure portal access, Visual Studio 2019, or Visual Studio Code.
  • Along with Azure Key Vault, we need an Azure App Registration in Azure Active Directory to access Key Vault secrets. Let’s create App registration first.

Create App Registration in Azure Active Directory

Open the Azure portal click the Azure Active Directory blade and click the “App registrations” tab.

Azure Active

Click the “New Registration” tab to create a new app registration.

We can give a valid name to app registration and click the Register button to proceed.

Keyvault

Please copy the Application ID (Client ID) to any secure place. We will use this ID in our Web API application later.

Object ID

We can create a client secret in this app registration. Click the “Certificates & secrets” tab.

Quickstart

Click the “New client secret” button to create a new client secret.

Certificate

We can give any description and create a client secret.

NEW Client

Please copy the above secret key and keep it in any secure place. We will use this value also in Web API applications.

We have successfully completed the app registration part and copied the required values like client ID and client secret value. We can create the Azure Key Vault now

Create Azure Key Vault and Secret Value

Click the Create New Resource button and choose “Key Vault”

Click the “Create” button

Create key vault

We can choose an existing resource group or create a new resource group. Please give a valid name to the key vault. Also, choose the appropriate region. I have kept all other fields as default. If you want to modify it, you can do it carefully.

Please click the “Review + Create” button. Your Key Vault will be deployed in a few moments.

IAM

There are three types of Key vaults available. Keys, Secrets, and Certificates. In this article, we will see Secrets only.

We can click “Secrets” to create a new secret key and value pair.

Click the “Generate/Import” button to create a new secret pair.

Activation

We can give a name and value to the secret.

Click the “Create” button to create a secret value pair.

We can grant access policies of this Key Vault to app registration, which we have created already.

Solve Problems

Click the “Access policies” tab to proceed.

Click “+ Add Access Policy”

Choose secret permissions and choose Get, List, Set, and Delete.

Configure

Select principal and search for our app registration name. We have already created an app registration. Select it and click the “Add” button.

Principal

We can see the selected app registration with secret permissions from Key Vault. We can save the permissions.

Discard

We have successfully created Azure Key Vault and Secret key-value pairs. We can create a Web application to consume these details and get secret values from Key Vault.

Create Web API Core application in Visual Studio 2019

We can create a simple Web API application with ASP.NET Core template.

Modify the appsettings.json with the below values.

Appsettings

We can install “Microsoft.Extensions.Configuration.AzureKeyVault” NuGet package to the project.

We can modify the “CreateHostBuilder “method in the Program.cs file.

Program. cs

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

namespace AzureKeyVaultSecret
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, config) =>
                {
                    var root = config.Build();
                    config.AddAzureKeyVault($"https://{root["KeyVault:Vault"]}.vault.azure.net/", root["KeyVault:ClientId"], root["KeyVault:ClientSecret"]);
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

We can create a new API controller “ValuesController” under the Controllers folder.

Modify the default code with the below code.

ValuesController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace AzureKeyVaultSecret.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        private readonly IConfiguration _configuration;

        public ValuesController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpGet]
        public string Get()
        {
            var value = _configuration["sarathsecret"];
            return "Value for Secret [sarathsecret] is : " + value;
        }
    }
}

We can run the application and execute the below endpoint.

https://localhost:44340/api/values

You will get the below value on the screen.

Localhost

We have successfully retrieved the value for Key Vault Secret into the Web API application.

Conclusion

In this post, we have created an app registration and also created a client secret for app registration. We have created a Key Vault with Secret and granted access permissions to app registration. Later we created an ASP.NET Core Web API and fetched the secret value from Key Vault using Client ID and Client secret key.