Add secrets.json to an Azure Function

I was surprised to see that .NET 8 Azure functions don’t include support for ASP.NET’s Secret Manager aka User secrets aka secrets.json out of the box.

Out of the box you get this:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =>
    {
        services.AddApplicationInsightsTelemetryWorkerService();
        services.ConfigureFunctionsApplicationInsights();
    })
    .Build();

host.Run();

To add user secrets, you’ll need to install the Microsoft.Extensions.Configuration.UserSecrets NuGet package, and then call .ConfigureAppConfiguration(), like so:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureAppConfiguration((hostContext, config) =>
    {
        if (hostContext.HostingEnvironment.IsDevelopment())
        {
            config.AddJsonFile("local.settings.json");
            config.AddUserSecrets<Program>();
        }
    })
    .ConfigureServices(services =>
    {
        services.AddApplicationInsightsTelemetryWorkerService();
        services.ConfigureFunctionsApplicationInsights();
    })
    .Build();

host.Run();

Edit: According to this page, User secrets are supported in Azure Functions Core Tools (version 3.0.3233 or later) – so maybe the above isn’t needed any more.

Leave a comment