How to use AppSettings.json in Azure Web App and Web API?

In App Service, app settings are variables passed as environment variables to the application code.

For ASP.NET and ASP.NET Core developers, setting app settings in App Service are like setting them in <appSettings> in Web.config or appsettings.json, but the values in App Service override the ones in Web.config or appsettings.json. You can keep development settings (for example, local MySQL password) in Web.config or appsettings.json and production secrets (for example, Azure MySQL database password) safely in App Service. The same code uses your development settings when you debug locally, and it uses your production secrets when deployed to Azure.

Let’s say we have this AppSettings file;

{
  "ConnectionStrings": {
    "MyDB": "Data Source=localhost;Initial Catalog=ZooDB;Persist Security Info=True;User ID=monkey;Password=pepepe",
    "MyLog": "Data Source=localhost;Initial Catalog=ZoodDBLog;Persist Security Info=True;User ID=banana;Password=eat"
  },
  "AllowedHosts": "*"

The connection settings on Azure Api App or Web App blade under configuration would be;

First Database

Name
MyDB

Value
Data Source=remotehost.com;Initial Catalog=ZooDB;Persist Security Info=True;User ID=remoteMonkey;Password=xxxee

Type
SQL Server

Second Database

Name
MyLog

Value
Data Source=remotehost.com;Initial Catalog=ZooDBLog;Persist Security Info=True;User ID=remoteMonkey;Password=xxxee

Type
SQL Server

Let’s say we have these hierarchal settings in AppSettings file;

"ApplicationSettings": {
    "CanImpersonate": "true",
    "GenerateJwt": "false",
    "ActiveDirectorySource": {
      "DataSource": "Database",
      "ActiveDirectory": {
        "Username": "variable",
        "Password": "variable",
        "DomainName": "variable",
        "EmailKey": "mail",
        "FirstNameKey": "givenName",
        "LastNameKey": "sn",
        "PhoneKey": "telephoneNumber",
      },
      "Database": {
        "ConnectionString": "Data Source=localhost;Initial Catalog=ZooDB;Persist Security Info=True;User ID=monkey;Password=pepepe",
        "Table": "ad.monkeytable",
      }
    },
"AllowedHosts": "*"

The connection settings on Azure Api App or Web App blade under configuration would be;

Name
ApplicationSettings:ActiveDirectorySource:Database:ConnectionString

Value
Data Source=remotehost;Initial Catalog=ZooDB;Persist Security Info=True;User ID=monkey;Password=pepepe

Type
SQLServer

If there are application settings other than connection string, they would be configured like this;

Name
ApplicationSettings__ActiveDirectorySource__Database__Table

Value
ad.monkeytable

The only difference between single and hierarchal structure is addition of : and __ qualifier’s (Two underscores connected).

When reading in ASP.NET core application, hierarchy can be stepped down with (:). for example;

# get value from appsettings
var logConnectionString = configuration.GetSection("ApplicationSetting:ConnectionStrings:LogDatabase");

#use the value
Console.WrtieLine(logConnectionString.Value);

If for some reasons, above configuration doesn’t work, try to publish to app service using Visual Studio publish feature. Make sure to add connection dependency manually.

Sources

https://techcommunity.microsoft.com/t5/apps-on-azure-blog/asp-net-core-appsettings-for-azure-app-service/ba-p/392596

https://docs.microsoft.com/en-us/azure/app-service/configure-common?tabs=portal

https://docs.microsoft.com/en-us/azure/app-service/configure-language-dotnetcore?pivots=platform-windows#access-environment-variables

Azure Key Vault with Azure Apps

I am going to create and configure Azure key vault in this demo. I am assuming that an app services has already been provisioned. We need to make a configuration change for SQL connection so that Key Vault secret can be used without touching the application code.

Provision the Azure Key Vault

For this demo, I am going to use new permission model that is based on Azure role-based access control (RBAC).

I am leaving it as Public endpoint to match the App service configuration.

Click on Review + Create button to start the deployment.

Once created, add yourself to the role “Key Vault Administrator” via the Access Control (IAM). Now you can start managing secrets.

Add the connection string to the Key Vault secrets.

Secret type (Upload options) “Manual”, give it a name and set the value to the SQL Database connection string to your Azure SQL or Azure SQL VM.

Click on Create. Once created, click on the secret to see the secret details, then click again on the current version.

Copy Secret Identifier to your clipboard.

Add the Secret identifier reference to the Azure App Service Settings

Open the App Service configuration settings, and ad a new Connection string setting.

Type the name of the connection string (“SqlConnectionString” for application) and set the value. You can use the same name that you have used in appsettings.json file. Set the value;

@Microsoft.KeyVault(SecretUri=VALUE_FROM_CLIPBOARD)

Click on Save to save the app settings.

Allow the App Service to access the Key Vault

On the App Service, click on Identity to enable the System Assigned identity. Click on save after turning “On” the status.

Click on the “Role Assignments” button and then click on the “Add role assignment”. In the role assignment, choose scope “Key Vault”, subscription the subscription where you created the Key Vault on previous steps and the name of the Key Vault resource. For the role just select “Key Vault Secrets User (preview)”

You can go to the appsettings.json/web.config file of your application and clear the connection string value;

Visit your website and see if it loads successfully. The connection string is safely stored in the Azure Key Vault, and it’s no longer stored on the file system.

Known issues

ERROR: You might get an error “Keyword not supported: ‘@microsoft.keyvault(secreturi'”. I have experienced that the RBAC permissions can take a one or two minutes to be applied, so try after a few minutes. Also try restarting the application thought the App Service portal so nothing is cached.

another error might be this;

ERROR: Format of the initialization string does not conform to specification starting at index 0.

Check your connection string. it has spaces or is not right.

Resources

https://docs.microsoft.com/en-us/azure/key-vault/general/security-overview

https://docs.microsoft.com/en-us/azure/key-vault/secrets/quick-create-portal

https://docs.microsoft.com/en-us/azure/key-vault/general/developers-guide

https://docs.microsoft.com/en-us/samples/azure-samples/key-vault-node-getting-started/quickstart-set-and-retrieve-a-secret-from-azure-key-vault-using-a-node-web-app/