{"id":3976,"date":"2023-11-04T23:13:58","date_gmt":"2023-11-04T23:13:58","guid":{"rendered":"http:\/\/localhost:10003\/managing-secrets-and-certificates-with-azure-key-vault\/"},"modified":"2023-11-05T05:48:25","modified_gmt":"2023-11-05T05:48:25","slug":"managing-secrets-and-certificates-with-azure-key-vault","status":"publish","type":"post","link":"http:\/\/localhost:10003\/managing-secrets-and-certificates-with-azure-key-vault\/","title":{"rendered":"Managing secrets and certificates with Azure Key Vault"},"content":{"rendered":"
In today’s world, secrets and certificates are critical components of any secure application or service. And if you’re running your services in the cloud, you need a secure and scalable way to manage your secrets and certificates. This is where Azure Key Vault comes into play.<\/p>\n
Azure Key Vault is a cloud-based service that provides a secure way to store and manage secrets, keys, and certificates. It integrates with both Azure and on-premises resources, allowing you to easily secure your applications and services.<\/p>\n
In this tutorial, we will explore how to manage secrets and certificates with Azure Key Vault. We will cover the following topics:<\/p>\n
Let’s get started!<\/p>\n
Before we can start managing secrets and certificates with Azure Key Vault, we need to create an Azure Key Vault instance. To do this, we will use the Azure Portal.<\/p>\n
Congratulations! You have created an Azure Key Vault instance.<\/p>\n
Now that we have a Key Vault, let’s add a secret. A secret is a secure value that can be used by your applications or services. Secrets can be anything from connection strings to API keys.<\/p>\n
That’s it! You have now added a secret to your Azure Key Vault. But how do we access this secret from our applications and services?<\/p>\n
To access the secret from your applications or services, you will need to authenticate with Azure Key Vault.<\/p>\n
Azure Key Vault supports several ways to authenticate, including Azure AD identities, certificates, and shared access signatures. In this tutorial, we will use Azure AD identities for authentication.<\/p>\n
To authenticate with Azure Key Vault using Azure AD identities, you will need to create an Azure AD application and assign it the appropriate permissions.<\/p>\n
Now that we have granted access to our Azure AD application, we can use the Azure Key Vault REST API to access our secret.<\/p>\n
GET https:\/\/{vault-name}.vault.azure.net\/secrets\/{secret-name}\/{secret-version}?api-version=7.2\nAuthorization: Bearer [access_token]\n<\/code><\/pre>\nThe access token must include the appropriate permissions that we assigned to our Azure AD application in the previous step.<\/p>\n
Here’s an example of how to access the secret using the Azure Key Vault PowerShell Module:<\/p>\n
$secret = Get-AzKeyVaultSecret -VaultName \"mykeyvault\" -Name \"mysecret\"\n$secretValue = $secret.SecretValueText\n<\/code><\/pre>\nThat’s it! You have now successfully accessed your secret from your application or service.<\/p>\n
Managing certificates in Azure Key Vault<\/h2>\n
In addition to secrets, Azure Key Vault also supports certificates. Certificates are used to secure communications between two parties by providing a trusted identity. Certificates can be used for a variety of purposes, including HTTPS, SSL\/TLS, and code signing.<\/p>\n
Let’s add a certificate to our Azure Key Vault instance.<\/p>\n
\n- Navigate to your Azure Key Vault instance in the Azure Portal.<\/li>\n
- Click on the “Certificates” blade in the left-hand menu.<\/li>\n
- Click on the “+ Add” button to add a new certificate.<\/li>\n
- Fill out the required information, including a name for your certificate, the certificate file, and a password if necessary.<\/li>\n
- You can also add optional metadata and tags to your certificate for better organization and searchability.<\/li>\n
- Click on the “Create” button to add the certificate to your Key Vault.<\/li>\n<\/ol>\n
Now that we have added the certificate to our Azure Key Vault instance, let’s use it to secure an Azure App Service.<\/p>\n
Using Azure Key Vault with Azure App Service<\/h2>\n
Azure App Service is a platform-as-a-service (PaaS) offering that allows you to easily deploy and scale web applications and APIs. App Service also supports integration with Azure Key Vault, allowing you to securely store and retrieve secrets and certificates.<\/p>\n
To use Azure Key Vault with Azure App Service, you will need to follow these steps:<\/p>\n
\n- Grant your Azure App Service access to your Azure Key Vault instance.<\/li>\n
- Update your web app or API to use the specified secrets and certificates.<\/li>\n<\/ol>\n
Let’s walk through these steps in more detail.<\/p>\n
Grant your Azure App Service access to your Azure Key Vault instance<\/h3>\n\n- Navigate to your Azure Key Vault instance in the Azure Portal.<\/li>\n
- Click on the “Access policies” blade in the left-hand menu.<\/li>\n
- Click on the “+ Add Access Policy” button to add a new access policy.<\/li>\n
- Select the “Certificate Management” permission and select the Azure AD application or user for your Azure App Service.<\/li>\n
- Click on the “Add” button to add the access policy.<\/li>\n<\/ol>\n
Now that we have granted access to our Azure App Service, we can use the Azure Key Vault REST API to access our certificate.<\/p>\n
Update your web app or API to use the specified secrets and certificates<\/h3>\n
To use your secrets and certificates with your web app or API, you will need to update your application code to retrieve the values from Azure Key Vault.<\/p>\n
Here’s an example of how to retrieve a secret from Azure Key Vault in .NET Core:<\/p>\n
using Azure.Extensions.AspNetCore.Configuration.Secrets;\nusing Azure.Identity;\nusing Microsoft.AspNetCore.Hosting;\nusing Microsoft.Extensions.Hosting;\n\npublic class Program\n{\n public static void Main(string[] args)\n {\n CreateHostBuilder(args).Build().Run();\n }\n\n public static IHostBuilder CreateHostBuilder(string[] args) =>\n Host.CreateDefaultBuilder(args)\n .ConfigureWebHostDefaults(webBuilder =>\n {\n webBuilder.UseStartup<Startup>()\n .ConfigureAppConfiguration((context, configBuilder) =>\n {\n var builtConfig = configBuilder.Build();\n var secretClient = new SecretClient(new(builtConfig[\"KeyVault:Url\"]),\n new DefaultAzureCredential());\n configBuilder.AddAzureKeyVault(secretClient, new());\n });\n });\n}\n<\/code><\/pre>\nThis code uses the AddAzureKeyVault<\/code> method from the Microsoft.Extensions.Configuration.AzureKeyVault NuGet package to retrieve the secrets from Azure Key Vault.<\/p>\nHere’s an example of how to retrieve a certificate from Azure Key Vault in .NET Core:<\/p>\n
using Azure.Identity;\nusing Azure.Security.KeyVault.Certificates;\nusing Azure.Security.KeyVault.Secrets;\nusing System.Security.Cryptography.X509Certificates;\n\nprivate async Task<X509Certificate2> GetCertificateAsync()\n{\n var secretClient = new SecretClient(new Uri(\"https:\/\/{vault-name}.vault.azure.net\/\"),\n new DefaultAzureCredential());\n\n var certificateClient = new CertificateClient(new Uri(\"https:\/\/{vault-name}.vault.azure.net\/\"),\n new DefaultAzureCredential());\n\n var secret = await secretClient.GetSecretAsync(\"my-cert-secret\");\n var certificate = await certificateClient.GetCertificateAsync(\"my-cert\");\n\n var certBytes = Convert.FromBase64String(secret.Value.Value);\n var privateKeyBytes = certificate.Value.Key.Export(CertificateKeyFormat.Pem);\n\n var certWithPrivateKeyBytes = new byte[certBytes.Length + privateKeyBytes.Length];\n Buffer.BlockCopy(certBytes, 0, certWithPrivateKeyBytes, 0, certBytes.Length);\n Buffer.BlockCopy(privateKeyBytes, 0, certWithPrivateKeyBytes, certBytes.Length, privateKeyBytes.Length);\n\n return new X509Certificate2(certWithPrivateKeyBytes, \"\",\n X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);\n}\n<\/code><\/pre>\nThis code uses the SecretClient<\/code> and CertificateClient<\/code> from the Azure SDK for .NET to retrieve the secret and certificate from Azure Key Vault, respectively. It then combines the private key with the certificate to create an X.509 certificate object.<\/p>\nThat’s it! You have now successfully secured your Azure App Service using certificates stored in Azure Key Vault.<\/p>\n
Using Azure Key Vault with Azure Functions<\/h2>\n
Azure Functions is a serverless compute service that allows you to run code on demand, without having to manage infrastructure. Like Azure App Service, Azure Functions also supports integration with Azure Key Vault.<\/p>\n
To use Azure Key Vault with Azure Functions, you will need to follow these steps:<\/p>\n
\n- Grant your Azure Function app access to your Azure Key Vault instance.<\/li>\n
- Update your function code to use the specified secrets and certificates.<\/li>\n<\/ol>\n
Let’s walk through these steps in more detail.<\/p>\n
Grant your Azure Function app access to your Azure Key Vault instance<\/h3>\n\n- Navigate to your Azure Key Vault instance in the Azure Portal.<\/li>\n
- Click on the “Access policies” blade in the left-hand menu.<\/li>\n
- Click on the “+ Add Access Policy” button to add a new access policy.<\/li>\n
- Select the “Certificate Management” permission and select the Azure AD application or user for your Azure Function app.<\/li>\n
- Click on the “Add” button to add the access policy.<\/li>\n<\/ol>\n
Now that we have granted access to our Azure Function app, we can use the Azure Key Vault REST API to access our certificate.<\/p>\n
Update your function code to use the specified secrets and certificates<\/h3>\n
To use your secrets and certificates with your function code, you will need to update your function bindings and\/or code to retrieve the values from Azure Key Vault.<\/p>\n
Here’s an example of how to retrieve a secret from Azure Key Vault in a C# function:<\/p>\n
using System.Threading.Tasks;\nusing Microsoft.Azure.Functions.Worker;\nusing Microsoft.Azure.Functions.Worker.Http;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Configuration.AzureKeyVault;\nusing Azure.Identity;\nusing Azure.Security.KeyVault.Secrets;\n\npublic static class MyFunction\n{\n [Function(\"MyFunction\")]\n public static async Task<HttpResponseData> RunAsync([HttpTrigger(AuthorizationLevel.Function, \"get\", \"post\")] HttpRequestData req,\n FunctionContext executionContext)\n {\n var config = new ConfigurationBuilder()\n .AddAzureKeyVault(new SecretClient(new Uri(Environment.GetEnvironmentVariable(\"KeyVaultEndpoint\")),\n new DefaultAzureCredential()), new DefaultKeyVaultSecretManager())\n .Build();\n\n var secretValue = config[\"my-secret\"];\n \/\/ Do something with secretValue\n\n var response = req.CreateResponse();\n await response.WriteStringAsync($\"Secret value: {secretValue}\");\n return response;\n }\n}\n<\/code><\/pre>\nThis code uses the AddAzureKeyVault<\/code> method from the Microsoft.Extensions.Configuration.AzureKeyVault NuGet package to retrieve the secrets from Azure Key Vault. Notice that we are passing in an instance of the SecretClient<\/code>, which we authenticate using the DefaultAzureCredential<\/code> class.<\/p>\nHere’s an example of how to retrieve a certificate from Azure Key Vault in a C# function:<\/p>\n
using System.Security.Cryptography.X509Certificates;\nusing System.Threading.Tasks;\nusing Microsoft.Azure.Functions.Worker;\nusing Microsoft.Azure.Functions.Worker.Http;\nusing Microsoft.Extensions.Logging;\nusing Azure.Identity;\nusing Azure.Security.KeyVault.Certificates;\nusing Azure.Security.KeyVault.Secrets;\n\npublic static class MyFunction\n{\n [Function(\"MyFunction\")]\n public static async Task<HttpResponseData> RunAsync([HttpTrigger(AuthorizationLevel.Function, \"get\", \"post\")] HttpRequestData req,\n FunctionContext executionContext)\n {\n var secretClient = new SecretClient(new Uri(Environment.GetEnvironmentVariable(\"KeyVaultEndpoint\")),\n new DefaultAzureCredential());\n var certificateClient = new CertificateClient(new Uri(Environment.GetEnvironmentVariable(\"KeyVaultEndpoint\")),\n new DefaultAzureCredential());\n\n var secret = await secretClient.GetSecretAsync(\"my-cert-secret\");\n var certificate = await certificateClient.GetCertificateAsync(\"my-cert\");\n\n var certBytes = Convert.FromBase64String(secret.Value.Value);\n var privateKeyBytes = certificate.Value.Key.Export(CertificateKeyFormat.Pem);\n\n var certWithPrivateKeyBytes = new byte[certBytes.Length + privateKeyBytes.Length];\n Buffer.BlockCopy(certBytes, 0, certWithPrivateKeyBytes, 0, certBytes.Length);\n Buffer.BlockCopy(privateKeyBytes, 0, certWithPrivateKeyBytes, certBytes.Length, privateKeyBytes.Length);\n\n var x509Cert = new X509Certificate2(certWithPrivateKeyBytes, \"\",\n X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);\n \/\/ Do something with x509Cert\n\n var response = req.CreateResponse();\n await response.WriteStringAsync($\"Certificate subject: {x509Cert.Subject}\");\n return response;\n }\n}\n<\/code><\/pre>\nThis code uses the SecretClient<\/code> and CertificateClient<\/code> from the Azure SDK for .NET to retrieve the secret and certificate from Azure Key Vault, respectively. It then combines the private key with the certificate to create an X.509 certificate object.<\/p>\nThat’s it! You have now successfully secured your Azure Function app using certificates stored in Azure Key Vault.<\/p>\n
Conclusion<\/h2>\n
In this tutorial, we explored how to manage secrets and certificates with Azure Key Vault. We created an Azure Key Vault instance, added a secret and certificate, and then used them to secure an Azure App Service and Azure Function app.<\/p>\n
By using Azure Key Vault to manage your secrets and certificates, you can easily secure your applications and services while scaling seamlessly in the cloud.<\/p>\n","protected":false},"excerpt":{"rendered":"
In today’s world, secrets and certificates are critical components of any secure application or service. And if you’re running your services in the cloud, you need a secure and scalable way to manage your secrets and certificates. This is where Azure Key Vault comes into play. Azure Key Vault is Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[658,657,662,661,660,659,656],"yoast_head":"\nManaging secrets and certificates with Azure Key Vault - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n