Managing secrets in asp.net core web applications part 2 : How to store secrets on production environment

In the first part of this series, I talked about how to store secrets while working locally on your development environment. In this post, I’ll walk you through how to do this when you deploy your applications.

Microsoft Azure has secret management offering called Azure key vault. We’ll be using azure key vault to manage secrets once we deploy our asp.net core web applications on non-local environments. This totally fits into the configuration model of asp.net core and you don’t have to change anything in the code you use to access secrets in your application (refer my last post).

Setup a key vault

You can go to Azure portal and set up a key vault using the portal or you can use Azure CLI to setup key vault through the command line.

Let’s add all our keys to the key vault. I have used Azure CLI here.

ScreenClip

Here is a snapshot of the key vault.

ScreenClip

Add azure key vault as a configuration source

Now the only step we need to take is to add azure key vault as one of the configuration sources.This will enable us to access all the key vault values transparently using ‘IConfiguration’ interface. Below is the code in the program.cs file.

Image

and your existing code will now fetch the values from key vault if ASPNETCORE_ENVIRONMENT variable is set to ‘Production’.

Image

Below is the output.

ScreenClip

Gotcha!

Don’t worry if this code does not work locally for some of you.

Also, did you think how this code is even working since there is nowhere you are authenticating with azure to access the azure key vault ?.

Well, we can’t go deep into this right now but I’ll drop a hint. Its called managed identities. Basically, when you deploy this code the concept of managed identity comes into the picture and it will work perfectly on a deployed environment. But the ‘Gotcha’ here is how does it work locally (and for some of you it might not work locally for this precise reason). Visual studio does a trick to make it work and for that, you need to be logged into the visual studio using the same account as your azure subscription through which you created key vault.

So if it does not work for you locally then try logging in using the correct account.

For further deep dive on these topics, you can look into this course by matt tester on pluralsight. And also this one on managed identities.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.