ASP.NET Core 2.0 Secret Manager

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,

  1. <ItemGroup>  
  2.   <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />  
  3. </ItemGroup>  

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