How To Authorize Your Key Vault Secrets and techniques To Serverless Azure Perform
Earlier than diving in, now we have already arrange a Key Vault on the Azure portal and now, we need to entry the saved secrets and techniques on Key Vault in our Azure Perform.
Nevertheless, you’re most likely questioning: “How do I take advantage of it?” Can I entry the Key Vault in the identical means as I did within the ASP.NET CORE internet utility?
The reply is NO. Do not you lose hope; we’re right here to demystify the key.
We will entry the Key Vault Secret in our Azure Perform in two alternative ways
- Utility settings from Key Vault
@Microsoft.KeyVault(SecretUri=secret_uri_with_version) Permitting Utility settings to entry KeyVault through secret URL
- Managed Identities for App Providers
By giving entry rights to our Azure Perform to entry the Key Vault secrets and techniques with the assistance of Secret URI
https://{title}.vault.azure.internet/secrets and techniques/{secretname})
Case Examine
Allow us to take a look at an instance the place we need to entry some secret keys in our Azure operate to realize our enterprise requirement. Contemplating that we are attempting to resolve a enterprise downside with this HTTP Set off Azure operate, allow us to do a proof of idea that the Azure operate needs to be an HTTP set off Azure operate. As soon as the person tries to eat the Azure operate, it ought to present these secret values within the response.
Listed here are the three necessities that you’ll uncover,
-
Configure the Azure operate to speak with Key Vault when deployed on the native improvement setting and Azure.
-
Find the place to retailer keys within the native improvement setting.
-
Discover ways to Deploy Azure operate on Azure.
Prerequisite
-
Energetic Azure subscription
-
-
Azure Perform
-
Azure Energetic Listing
-
Key Vault
-
How can we proceed?
Breaking down the issue into smaller chunks first that’s how we will probably be continuing forward step-by-step,
- Create your first HTTP Set off Azure operate. In case you are not conscious of HTTP Set off features, my sincere suggestion will to go and skim this text HTTP Set off Azure Perform(Serverless Computing).
- Create a Service Library which can work together with Key Vault.
- Entry the worth from native.settings.json in our improvement setting.
- Create Azure Assets wanted for this Demo.
- Present Key Vault entry id to the Perform app utilizing the PowerShell command, manually from the portal.
Let’s get began and create our Azure operate utilizing Visual Studio.
Choose HTTP Set off Template and choose Azure Features V1 as a result of, in model V2, I had some points with the HTTP set off operate after I examined on my native machine whereas scripting this.

Template generated code for HTTP set off.
- utilizing System.IO;
- utilizing Microsoft.AspNetCore.Mvc;
- utilizing Microsoft.Azure.WebJobs;
- utilizing Microsoft.Azure.WebJobs.Extensions.Http;
- utilizing Microsoft.AspNetCore.Http;
- utilizing Microsoft.Azure.WebJobs.Host;
- utilizing Newtonsoft.Json;
- namespace AzFuncKeyVaultIntegration
- {
- public static class Function1
- {
- [FunctionName(“Function1”)]
- public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, “get”, “post”, Route = null)]HttpRequest req, TraceWriter log)
- {
- log.Data(“C# HTTP set off operate processed a request.”);
- string title = req.Question[“name”];
- string requestBody = new StreamReader(req.Physique).ReadToEnd();
- dynamic information = JsonConvert.DeserializeObject(requestBody);
- title = title ?? information?.title;
- return title != null
- ? (ActionResult)new OkObjectResult($“Hey, {title}”)
- : new BadRequestObjectResult(“Please cross a title on the question string or in the request physique”);
- }
- }
- }
Now, let’s create a Service Library which may have all accountability of calling Key Vault APIs and return us the precise worth of our secret keys.
Creating a brand new Class Library from our answer


Set up the beneath packages to work together with Key Vault from our companies library from NuGet.
- Microsoft.Azure.Providers.AppAuthentication Model:1.0.3
- Microsoft.Extensions.Configuration.AzureKeyVault Model: 2.2.0
As soon as performed, create a category named KeyVaultService placing within the beneath code snippet.
- utilizing Microsoft.Azure.KeyVault;
- utilizing Microsoft.Azure.Providers.AppAuthentication;
- utilizing System;
- utilizing System.Threading.Duties;
- namespace Providers
- {
- public class KeyVaultService
- {
- public async Job GetSecretValue(string keyName)
- {
- string secret = “”;
- AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
- var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
- var secretBundle = await keyVaultClient.GetSecretAsync(Setting.GetEnvironmentVariable(“keyvault”) + keyName).ConfigureAwait(false);
- secret = secretBundle.Worth;
- Console.WriteLine(secret);
- return secret;
- }
- }
- }
Now, reference the service library in your Azure Perform undertaking.

So now, let’s take into account I’ve created two secrets and techniques in Azure Key Vault; for instance:
- applicationSecret2
- secret2
Now I need to entry the Key Vault secret applicationSecret2 with the assistance of managed identities and one other secret, secret2, with the assistance of Key Vault references for Utility Settings on Azure.

Entry the App settings keys worth and name the Service operate (GetSecretValue) in Perform code,
- utilizing System;
- utilizing System.Linq;
- utilizing System.Internet;
- utilizing System.Internet.Http;
- utilizing System.Threading.Duties;
- utilizing Microsoft.Azure.WebJobs;
- utilizing Microsoft.Azure.WebJobs.Extensions.Http;
- utilizing Microsoft.Azure.WebJobs.Host;
- utilizing Providers;
- namespace AzFuncKeyVaultIntegrationM
- {
- public static class Function1
- {
- [FunctionName(“Function1”)]
- public static async Job Run([HttpTrigger(AuthorizationLevel.Function, “get”, “post”, Route = null)]HttpRequestMessage req, TraceWriter log)
- {
- log.Data(“C# HTTP set off operate processed a request.”);
- KeyVaultService _service = new KeyVaultService();
- string secretValue = await _service.GetSecretValue(“applicationSecret2”);
- log.Data(“Secret worth retrived through Secret Uri” + secretValue);
- string title = req.GetQueryNameValuePairs()
- .FirstOrDefault(q => string.Examine(q.Key, “title”, true) == 0)
- .Worth;
- if (title == null)
- {
- dynamic information = await req.Content material.ReadAsAsync();
- title = information?.title;
- }
- return title == null
- ? req.CreateResponse(HttpStatusCode.BadRequest, “Please cross a title on the question string or in the request physique”)
- : req.CreateResponse(HttpStatusCode.OK, $“Hey {title} utilizing keyvault Syntax from app settings {Setting.GetEnvironmentVariable(“secret2“)}”);
- }
- }
- }
Let’s run our utility in our improvement setting. Now test whether or not our Perform app is ready to retrieve the secrets and techniques or not.

With a view to eat this HTTP set off Azure operate, I will probably be utilizing the Postman Relaxation HTTP shopper. We’ll eat the “http://localhost:7071/api/Function1” endpoint.


Configure Utility Settings from Key Vault on Azure
We’re efficiently in a position to run our utility from our improvement setting. Now we are going to deploy our utility on Azure and attempt to entry secret secret2 from Key Vault in utility settings. This characteristic works that equally as we’re simply utilizing AppSetting key-value pair however internally it retrieves the worth from Key Vault. With a view to make this work, now we have to configure the entry coverage to Perform App, as soon as we deploy our Perform app.
Allow us to first deploy our Azure operate on Azure Portal utilizing Visual Studio:

As I haven’t got any Azure App Service on Azure I’ll create a brand new Azure App Service step-by-step,

Click on on Publish.

Then click on on Create. Visual Studio will publish our utility now. As soon as that is accomplished the Azure operate will probably be revealed, and we will test the standing in an Output window.

Let’s now login to the Azure portal to see if our Perform app has been created or not.

Assign your operate app entry to the Key Vault step-by-step,


As soon as you’re performed click on on OK and save the entry coverage.
As soon as performed now allow System Id as a way to authenticate to cloud companies (e.g. Azure Key Vault, Energetic Listing).
- Go to operate app settings.
- Click on on platform options.
- Click on on Id options within the checklist.

Allow us to now first get the secret_uri_with_version for secret named applicationSecret1 which will probably be saved in the secret2 key in appSettings.
Go to the Key Vault useful resource that you just need to eat after which click on on Secret. Now in our operate app, I need to use the worth of my applicationSecret1 secret which is configured in my (setting variable or AppSettings) on Azure as secret2.

Now Click on on applicationSecret1 and you may be navigated to model blade view as proven beneath:

Click on on the Present Model row and now copy the Secret identifier worth from the brand new web page as proven beneath:

Now return to the operate app and create a brand new utility variable/utility setting named “secret2” and put the worth within the given format along with your secret URL that we simply copied, additionally add different utility setting keys and values which can be required for the operate app like DNS which was current within the native.settings.json file.

Format of Key Vault Worth for secret
@Microsoft.KeyVault(SecretUri=secret identifier worth)
As soon as all steps are accomplished save the appliance settings and let’s attempt to eat the deployed Azure operate from Postman now.
Click on on Function1 after which click on on get operate URL and duplicate the URL:


Hit the URL from POSTMAN and you will note the worth retrieved from the Key Vault.

So you possibly can see how simply step-by-step we realized “methods to Authorize your Key Vault Secrets and techniques to Serverless Azure Perform”
Watch right here a full video to be taught extra about Serverless Computing.
I hope you loved studying the article as a lot as I did scripting this up.
For those who did, go away your ideas within the feedback beneath.
Additionally, I’ll like it for those who share the article in your most well-liked social media platform.
References