Azure

Automate Azure Key Vault Key Refresh with Managed Identification

Abstract

In fashionable software program growth, safety practices usually contain securely managing and often updating cryptographic keys used for authentication and encryption. Azure Features supplies a robust serverless computing platform that may be leveraged to automate duties like key refreshing. On this article, we’ll show the best way to create an Azure Perform in C# that retrieves public keys from a JWKS (JSON Internet Key Set) endpoint and shops them securely in Azure Key Vault.

Stipulations

Earlier than we begin, be sure you have the next conditions arrange.

  1. Azure Subscription: You may want an Azure account to create Azure Key Vault.
  2. Azure Key Vault: Create an Azure Key Vault occasion the place the keys will likely be saved securely.
  3. Azure Features: Arrange an Azure Features software in your Azure portal.

Setup Azure Key Vault

Microsoft

Overview

Keyvault

Create a secret and put any random worth in my case I’ve put the worth asif123.

Secret

Azure

See the present model of the Secret.

Current version

Present the Secret Worth

Secret Value

Copy Shopper ID & Tenant ID out of your Registered App from Microsoft Entra ID.

Entra ID

Now go to the Internet browser and place Tenant ID and Shopper ID to get the JWKS from Microsoft Entra ID.

https://login.microsoftonline.com/Your_Tenant_ID/discovery/keys?appid=Your_Application_ID

 Tenant ID

Establishing the Azure Perform

We’ll create a C# Azure Perform app that makes use of the HttpClient to fetch keys from a JWKS endpoint after which securely shops them in Azure Key Vault.

Create an Azure Perform App in Azure Portal by following the steps.

Azure Function

Azure App

Create Function

Resource

Now Enabling Handle Identification on Azure Perform App.

Function App

System

Yes

On

Create Azure Perform from Visual Studio.

Visual Studio

Copy the URL from browser

 Browser

Copy the Key Vault URL

Vault URL

Create Azure Perform in Visual Studio.

Create Azure

Go to the file and paste the copied URLs in highlighted locations.

 Highlighted places

copy the next code and exchange the highlighted values.

utilizing System.IO;
utilizing System.Internet.Http;
utilizing System.Threading.Duties;
utilizing Microsoft.AspNetCore.Http;
utilizing Microsoft.AspNetCore.Mvc;
utilizing Microsoft.Azure.WebJobs;
utilizing Microsoft.Azure.WebJobs.Extensions.Http;
utilizing Microsoft.Extensions.Logging;
utilizing Azure.Identification;
utilizing Azure.Safety.KeyVault.Secrets and techniques;
utilizing Newtonsoft.Json.Linq;
utilizing System;
utilizing static System.Internet.WebRequestMethods;

namespace az_function_app_key_refresher
{
    public static class KeyRefreshFunction
    {
        non-public static readonly HttpClient httpClient = new HttpClient();

        [FunctionName("KeyRefreshFunction")]
        public static async Activity<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("Refreshing Public key.");

            // Fetch JWT keys from JWKS endpoint
            string jwksEndpoint = "https://login.microsoftonline.com/3ed13bce-637a-48c0-9488-1d296357a694/discovery/keys?appid=974b51ab-3fc7-4194-8295-66fc2c020a57";
            string jwksJson = await httpClient.GetStringAsync(jwksEndpoint);
            var jwks = JObject.Parse(jwksJson);

            // Retailer JWT keys in Azure Key Vault
            await StoreKeysInKeyVault(jwks, log);

            return new OkObjectResult("Public key refreshed and saved in Azure Key Vault.");
        }

        non-public static async Activity StoreKeysInKeyVault(JObject jwks, ILogger log)
        {
            var secretClient = new SecretClient(new Uri("https://azure-function-app-key-refresher.azurewebsites.web"), new DefaultAzureCredential());
            string secretName = "mysecret";

            foreach (var key in jwks["keys"])
            {
                string keyId = key["kid"].ToString();
                string keyJson = key["x5c"].ToString().Substitute('[',' ').Replace('"',' ').Replace('"',' ').Replace(']',' ').Trim();

                // Retailer the important thing in Azure Key Vault
                await secretClient.SetSecretAsync(secretName, keyJson);
                log.LogInformation($"Saved key with ID {keyId} in Azure Key Vault.");
                break;
            }
        }
    }
}

Run the Azure Perform with F5 from Visual Studio within the Native atmosphere and you may check it regionally by signing in from Visual Studio to your Azure Portal.

Azure portal

Copy the URL and paste it into the Postman and execute this utilizing Get request.

 Postman

http://localhost:7193/api/KeyRefreshFunction

Fresh Function

Once you execute this request from Postman.

Send

you’re going to get the message on the console as highlighted beneath.

Console

Now go to the Azure portal go to the key and click on on it.

Learn

Now you possibly can see that there are two variations of secret and secret factors to the present model.

Mysecret

You possibly can see the key worth that has a brand new worth that was extracted from the JWKS URL.

 JWKS URL

Efficiently refreshed the key at Azure Key Vault from Azure Perform that was regionally executed utilizing Managed Identification.

Abstract

This text outlines the method of automating key refreshing in Azure Features utilizing C# to securely handle and replace cryptographic keys fetched from a JWKS (JSON Internet Key Set) endpoint and retailer them in Azure Key Vault. The article emphasizes fashionable safety practices in software program growth and using serverless computing for automation.

Key Factors Lined

  • Safety Practices: Emphasizes the significance of securely managing and updating cryptographic keys for authentication and encryption in fashionable software program growth.
  • Azure Companies Used: Demonstrates the mixing of Azure Features and Azure Key Vault to automate key refreshing duties.
  • Stipulations: Lists the conditions required to arrange the Azure Perform and Azure Key Vault, together with an Azure subscription and Azure Features software.
  • Setup of Azure Key Vault: Gives step-by-step directions on organising Azure Key Vault, making a secret, and accessing the key worth.
  • Azure Perform Configuration: Particulars the creation and configuration of an Azure Perform app utilizing Visual Studio, enabling managed id, and integrating with Azure Key Vault.
  • Code Implementation: Presents a C# code snippet for the Azure Perform (`KeyRefreshFunction`) that retrieves keys from a JWKS endpoint utilizing `HttpClient` and shops them securely in Azure Key Vault utilizing SecretClient.
  • Testing Domestically: Guides on operating and testing the Azure Perform regionally from Visual Studio and Postman, showcasing the profitable execution of key refreshing utilizing managed id.
  • Consequence: Concludes with the profitable refresh of the Azure Key Vault secret, demonstrating efficient automation of key administration duties inside a safe atmosphere.

Total, this abstract encapsulates the method of implementing automated key refreshing in Azure Features, highlighting finest practices in safety and Azure companies integration for safe key administration in cloud-based purposes.

Know extra about our firm at Skrots. Know extra about our companies at Skrots Companies, Additionally checkout all different blogs at Weblog at Skrots

Show More

Related Articles

Leave a Reply

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

Back to top button