Advanced Ajapa Yoga Kriyas and Meditations for Software Developers : Tap the power of breath, mantra, mudra, and dhyana for improved focus, peace of mind, and blissful inner connection.


Store connection string in Azure App Service and Azure Key Vault

In the previous article you learned to deploy an ASP.NET Cor web app in an Azure App Service using two techniques. Recollect that we are storing the database connection string in the appsettings.json file. And we need to change it to match the production setup at the time of deployment.

In this article we will discuss two better ways of storing the database connection string. Firstly, we will learn to store the connection string into the Azure App Service itself. And then we will store it in Azure Key Vault.

To store the database connection string in the Azure App Service, sign-in to the Azure portal and then navigate to the Web App you created in the previous example.

Then locate Environment Variables from the left side options.

Then switch to the Connection Strings tab.

Click on the Add option to open the Add / Edit connection string dialog.

Here, enter Name exactly same as what you used in your web application code. In our example, we have used AppDb as the connection string name in the appsettings.json and hence here also we will keep it the same. Also, enter the database connection string of the Northwind Azure SQL database in the Value textbox (shown empty in the figure). Finally, set type to SQLServer.

The following figure shows AppDb successfully added to the list of connection strings.

Now, open the web application using Visual Studio Code and change the AppDb connection string from production back to development / local setup.

Redeploy the web application as explained in the previous article. This time although our appsettings.json contains the development / local database connection string the web app will load as expected because it automatically picks the AppDb connection string defined in the Azure App Service.

In the preceding example we stored the connection string in the Azure App Service itself. This way you need not share the production connection string with the development team. The development team can work with their local databases and after the deployment the connection string stored in the App Service will be automatically used.

At times you need a more secure way to store the database connection string. In such cases you can store the database connection string in Azure Key Vault. As the name suggests Azure Key Vault is a cloud based secure storage where you can store sensitive data including connection strings. The stored information can be retrieved from your ASP.NET Core apps using Azure Key Vault libraries for .NET, a set of NuGet packages.

We will modify our example to use Azure Key Vault. To begin the modification, we will create a Key Vault and store our connection string in it using Azure Portal.

Sign-in to the Azure portal and search for Key Vault.

On the Key Vaults page create a new Key Vault.

Fill in all the details such as resource group, key vault name, region, and pricing.

Complete the key vault creation by clicking on the Create button and following the on-screen instructions.

After creating the key vault, we will create a secret for storing the database connection string.

Go to the key vault page and click on the Secrets menu option from the left hand menus.

Create a new secret named AppDb and set its value to the database connection string (Azure SQL database) as per your setup.

Save the newly created secret and ensure that it appears in the list of secrets. Check its value in case you wish to confirm that it has been assigned correctly.

Now we have our web app and we also have our key vault. Next, we need to grant access to our web app to read the key vault secret we just created.

Go to the Azure web app and locate the Identity menu option from the left side menus.

Under System Assigned tab, change the status to On and copy the Object ID / Principal ID that is generated for you.

Come to the key vault page again, and look for the Access Policies menu option.

Create a new Access Policy with Get and List secret permissions.

In the Principal selection step, search for the Object ID / Principal ID you copied earlier and pick that from the search results.

Complete the Create Access Policy wizard by following the on-screen instructions.

Now your Azure web app can read the connection string stored in the key vault.

Earlier we used database connection string stored in appsettings.json and Azure App Service. So, it was possible to configure the AppDbContext in Program.cs itself with this line of code :

builder.Services.AddDbContext
<AppDbContext>
(options => options.UseSqlServer(connStr));

Since we are now storing the connection string in Azure key vault we need to write some code to retrieve that connection string. This requires some change in the AppDbContext class.

First, add this configuration setting in the appsettings.json file.

"KeyVault": {
    "VaultUri": "https://*****.vault.azure.net/"
}    

Make sure to replace ***** with your key vault URL. You will find your key vault URL on the Overview page of the key vault.

Here, we store the key vault URL in a configuration section named KeyVault. We need this key vault URL while registering the Azure SecretClient :

builder.Services.AddAzureClients
(o =>
{
    o.AddSecretClient
    (builder.Configuration.
    GetSection("KeyVault"));
});    

Now open the AppDbContext.cs file and modify it as shown below:

public class AppDbContext : DbContext
{
    private readonly SecretClient secretClient;

    public AppDbContext(SecretClient secretClient) : base() 
    { 
        this.secretClient = secretClient;
    } 

    protected override void OnConfiguring
    (DbContextOptionsBuilder optionsBuilder)
    {
        
        KeyVaultSecret keyValueSecret = 
        secretClient.GetSecretAsync("AppDb").Result;
        var connStr = keyValueSecret.Value;
        optionsBuilder.UseSqlServer(connStr);
        
    }
    public DbSet<Employee> Employees { get; set; }
}

This code injects a SecretClient object into the AppDbContext. Inside the OnConfiguring() method we read the AppDb secret using the GetSecretAsync() method of SecretClient. This AppDb value is then used with UseSqlServer() to connect with the Azure SQL Server database.

This completes the modifications. Redeploy the web app again using any of the two techniques learned earlier. Run the web app again and confirm that it runs as expected.

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a meditation teacher and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his ASP.NET online courses go here. More details about his Ajapa Japa and Shambhavi Mudra online course are available here.

Posted On : 02 September 2024







Advanced Ajapa Yoga Kriyas and Meditations for Software Developers : Tap the power of breath, mantra, mudra, and dhyana for improved focus, peace of mind, and blissful inner connection.