Problem

Securely store the configuration settings without exposing them to the source control in ASP.NET Core.

Solution

Create an empty project and right-click on the Project Solution. Click “Manager User Secrets”:

This will open the secrets.json file. Add a setting name/value pair.

Add a POCO for these application settings.

Then, inject the configuration settings in the constructor for Startup class.

Then, add option services to the ConfigureServices() method of Startup class.

Next, inject settings as IOptions<T> interface, where T is your POCO for Settings.

Setup the middle in Configure() method of the Startup class.

Running the sample application will give you the following output.


Discussion

I discussed in the previous post how configuration settings can be stored in configuration files. However, these files are checked in the source control and are not suitable to store confidential settings. In a production environment, these settings can be stored in environment variables or Azure Key Vault, however, for development, ASP.NET Core provides an alternate solution: Secret Manager.

Secret Manager lets developers store the configuration settings in secrets.json file which isn’t checked-in the source control. The secrets.json file is stored in AppData folder and you could see the exact path by hovering your mouse over the file tab in VS 2017. An important point to note here is that the settings are stored in plain text. This file is read by the runtime when loading configuration during building the WebHost, as discussed here.

CLI

You could also use the CLI command dotnet user-secrets to manage the secret settings. In order to do that, first add the following to .csproj,

Now, you could use the following commands to manage the secrets.

CommandDescriptionExample
listList all the secretsdotnet user-secrets list
setAdd/update user secretdotnet user-secrets set SecretSetting “SecretValue”
removeRemoves a secretdotnet user-secrets remove SecretSetting
clearRemove all secretsdotnet user-secrets clear

Source Code

GitHub

Next Recommended Readings