Giter VIP home page Giter VIP logo

azure-function-keyvault's Introduction

Azure KeyVault Extensions for Azure Functions v2

About

This repo contains extensions for Azure KeyVault in Azure Function v2. It uses the Microsoft.Extensions.Configuration.AzureKeyVault library to include Azure KeyVault into the configuration of your Azure Functions. This lets you use Azure KeyVault with existing bindings on all AutoResolve properties, as well as properties that are filled from the configuration, e.g. connection strings. In addition you can use the AzureKeyVaultClient to get an IKeyVaultClient instance into your function.

Since this extensions uses the existing configuration provider, all requirements and restrictions are also valid for this extension.

Example usage:

[FunctionName("Function1")]
public static void Run(
    [BlobTrigger("%blobpath%", Connection = "storageconnection")]Stream myBlob,
    string name,
    ILogger log,
    [AzureKeyVaultClient]IKeyVaultClient client)
{
    log.LogInformation($"API Version: {client.ApiVersion}");
    log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
}

Values for blobpath and storageconnection are now also pulled from Azure KeyVault, if there are no values present in the normal config. The AzureKeyVaultClient Attributes binds an instance of an IKeyVaultClient into the function for advanced usage.

How to configure

The Azure KeyVault extensions are available as a nuget package. Once the package is added to function project, a WebJobsStartup is needed to register and configure the the extension.

This is an example WebJobsStartup class

using ExampleFunction;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Willezone.Azure.WebJobs.Extensions.AzureKeyVault;

[assembly: WebJobsStartup(typeof(Startup))]
namespace ExampleFunction
{
    public class Startup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            // Create temporary service provider to access configuration.
            var tempProvider = builder.Services.BuildServiceProvider();
            var config = tempProvider.GetRequiredService<IConfiguration>();
            builder.AddAzureKeyVault(config["AzureKeyVault_Uri"]);
        }
    }
}

The nuget package contains two extension methods to register the extensions.

AddAzureKeyVault(this IWebJobsBuilder builder, string vault, string clientId, string clientSecret)

This configures the extension to use a client id and client secret to access the KeyVault.

AddAzureKeyVault(this IWebJobsBuilder builder, string vault)

This configures the extension to use managed service identity to access the KeyVault

Azure Deployment

Currently there is an issue when publishing your function application that the required extensions.json is not created correctly. The issue is discussed here. Luckily there is a workaround for this: Just copy the Directory.Build.targets file into your Azure Functions project, this will then create the correct extensions.json file.

azure-function-keyvault's People

Contributors

boriswilhelms avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

azure-function-keyvault's Issues

Existing IConfiguration from builder.Services is lost

Not sure when this started, but I am using v3 Azure Functions and when the below code runs, the ImplementationInstance is always null on the ServiceDescriptor. Perhaps the behavior has changed under the covers in recent versions, but it now requires calling BuildServiceProvider() and fetching the IConfguration from the IServiceProvider. The impact of this is that any modifications I make to host.json is lost when also using this package.

var descriptor = builder.Services.FirstOrDefault(d => d.ServiceType == typeof(IConfiguration));
if (descriptor?.ImplementationInstance is IConfigurationRoot configuration)
{
    configurationBuilder.AddConfiguration(configuration);
}

After calling builder.AddAzureKeyVault() custom function route Prefix is reset to default

I have a custom prefix set up for my function in host.json file:
{ "version": "2.0", "extensions": { "http": { "routePrefix": "" } } }

So this means there should be no prefix and my function URL should look like
https://<hostname>/myendpoint
instead of default "api" prefix
https://<hostname>/api/myendpoint

But whenever I call builder.AddAzureKeyVault(...) in my Startup the custom prefix value is not taken into account and the default 'api' prefix is added

Thanks!

KeyVaultClient base URL

When using the KeyVaultClient like this in my Startup.cs:

public class Startup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            var tempProvider = builder.Services.BuildServiceProvider();
            var config = tempProvider.GetRequiredService<IConfiguration>();

            builder.AddAzureKeyVault(config["KeyVaultUrl"],
                "...",
                "...");
        }

and then like this in my function:

[FunctionName("RecognizeTextFromImage")]
        public static async Task Run(
            [EventGridTrigger]
            EventGridEvent eventGridEvent,

            [Blob("invoice-texts", FileAccess.Read)]
            CloudBlobContainer blobDirectory,

            [AzureKeyVaultClient]
            IKeyVaultClient keyVaultClient,

            ILogger log)
{
   keyVaultClient.GetSecretAsync("CognitiveServicesEndpoint")
   ...
}

I would expect that the keyVaultClient instance already uses the KeyVaultUrl as the base URL.
However, this is not the case right now and we need to pass it in:
keyVaultClient.GetSecretAsync(Environment.GetEnvironmentVariable("KeyVaultUrl") ,"CognitiveServicesEndpoint"))

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.