Home > Software engineering >  How to read appsettings.json value in ConfigureAppConfiguration (Azure function startup.cs)
How to read appsettings.json value in ConfigureAppConfiguration (Azure function startup.cs)

Time:07-11

I have an Azure Function App that reads the value of appsettings.json and replaces part of the secret with Azure Key Vault

However, the URI and userAssignedClientId used by KeyVault need to get the value from the appsetting.json file according to the environment

How should I change the URI and userAssignedClientId here to come from appsettings.json

This is my Startup.cs

using Azure.Extensions.AspNetCore.Configuration.Secrets;
using Azure.Identity;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;

[assembly: FunctionsStartup(typeof(FunctionApp3.Startup))]
namespace FunctionApp3
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddOptions<Settings>()
                .Configure<IConfiguration>((settings, configuration) =>
                {
                    configuration.GetSection("Settings").Bind(settings);
                });
        }

        public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
        {
            FunctionsHostBuilderContext context = builder.GetContext();

            string userAssignedClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; //Here
            var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = userAssignedClientId });

            var options = new AzureKeyVaultConfigurationOptions { ReloadInterval = TimeSpan.FromHours(24) };

            builder.ConfigurationBuilder
                .AddJsonFile(Path.Combine(context.ApplicationRootPath, "appsettings.json"), optional: true, reloadOnChange: false)
                .AddJsonFile(Path.Combine(context.ApplicationRootPath, $"appsettings.{context.EnvironmentName}.json"), optional: true, reloadOnChange: false)
                .AddEnvironmentVariables()
                .AddAzureKeyVault(new Uri("https://xxxxxxxx.vault.azure.net/"), credential, options); //Here

        }
    }
}

CodePudding user response:

How to read appsettings.json value in ConfigureAppConfiguration

  1. Add some value in local.settings.json
 "userAssignedClientIdValues": "user_Assigned_ClientId_Values",
  "IsEncrypted": false,
  "URLValue": "https://xxxxxx.vault.azure.net/",
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  }
}
  1. Add Startup.cs class in Azure Function.
  2. Add following code in Startup.cs Class
using Azure.Identity;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureKeyVault;
using Microsoft.Extensions.DependencyInjection;
using NuGet.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

[assembly: FunctionsStartup(typeof(FunctionApp7.Startup))]
namespace FunctionApp7
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddOptions<Settings>().Configure<IConfiguration>((settings, configuration) =>
            {
                configuration.GetSection("Settings").Bind(settings);
                
            });
        }

        public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
        {
           
            FunctionsHostBuilderContext context = builder.GetContext();
            System.Uri urlvalue = new Uri(config["URLValue"]);
            var config = new ConfigurationBuilder()
                 .SetBasePath(Directory.GetCurrentDirectory())
                 .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                 .AddEnvironmentVariables()
                 .Build();

            var appSettingValue = config["userAssignedClientIdValues"];

            string userAssignedClientId = ""; // Here
            var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = userAssignedClientId });

            var options = new AzureKeyVaultConfigurationOptions { ReloadInterval = TimeSpan.FromHours(24) };

            builder.ConfigurationBuilder
                .AddJsonFile(Path.Combine(context.ApplicationRootPath, "appsettings.json"), optional: true, reloadOnChange: false)
                .AddJsonFile(Path.Combine(context.ApplicationRootPath, $"appsettings.{context.EnvironmentName}.json"), optional: true, reloadOnChange: false)
                .AddEnvironmentVariables()
                .AddAzureKeyVault(new Uri("https://storeimportanvalues.vault.azure.net/").ToString(), credential.ToString(), options.ToString()); //Here

        }
    }
}

Output enter image description here

CodePudding user response:

If you have these app settings defined:

{
  ...
  "userAssignedClientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "vaultUri": "https://xxxxxxxx.vault.azure.net/"
  ...
}

You could retrieve the existing configuration like that:

public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
{
    // Build the exsting configuration
    var config = builder.ConfigurationBuilder.Build();

    // Retrieve values
    var userAssignedClientId = config["userAssignedClientId"];
    var vaultUri = config["vaultUri"];
    
    ...
}
  • Related