ASP.NET Core 2.0 Secret Manager

Problem

How do you securely store configuration settings without exposing them to source control in ASP.NET Core.

Solution

Create an empty project and right-click on project solution and 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 configuration settings in the constructor for Startup class:

Then add option services in ConfigureServicees() 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 Startup class:

Running the sample application give you 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 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 let developers store configuration settings in secrets.json file, which isn’t checked-in the source control. The secrets.json file is stored in AppData folder, you could see the exact path by hovering your mouse over the file tab in VS 2017. An important point to note 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:

Command Description Example
list List all the secrets dotnet user-secrets list
set Add/update user secret dotnet user-secrets set SecretSetting “SecretValue”
remove Removes a secret dotnet user-secrets remove SecretSetting
clear Remove all secrets dotnet user-secrets clear

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Security.SecretManager

Leave a Reply