JumpStart # 50 – User Secrets in ASP.Net Core

Most of the time we maintain project specific confidential credentials like Database connection strings, passwords etc., in configuration files. This sensitive information will be pushed to source version control servers like Team foundation server with regular check-ins. This is a bad practice because the sensitive information will be at risk (especially in case of public repositories). In this jumpstart, we are going to see how to use User Secret Manager Tool of .Net Core which provides a way to store sensitive data outside code files.

Important:

  1. Secret Manager Tool is not recommended to manage sensitive information on production servers. It is only recommended for development machines.
  2. Secret Manager Tool will maintain specified secrets in a JSON file under %APPDATA% folder on local machine.
  3. Information stored using this tool is not encrypted.
  4. Secret Manager Tool keys will override all the matched keys specified in appSettings.json file (or in any other configuration file).

This tutorial is executed using below Dotnet CLI version.

NOTE: Updated this tutorial on 2/26/2017 with MSBuild based Dotnet SDK.

image

To get Secret Manager Tool, add the following tool to CSProj file (right click project in VS 2017 and select Edit CSProj).

<ItemGroup>
  <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0-msbuild3-final" />
  <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0-msbuild3-final" />
</ItemGroup>

To identify user secrets uniquely for a project, we need to add a userSecretsId to CSProj as shown below.

<PropertyGroup>
  <TargetFramework>netcoreapp1.0</TargetFramework>
  <UserSecretsId>aspnet-WebApplication1-78ac8171-bcf0-44ff-9218-5d9e97974fce</UserSecretsId>
</PropertyGroup>

To configure MVC Core application to use User Secrets, we need to add following package to CSProj.

<ItemGroup>
  <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
  <PackageReference Include="Microsoft.AspNetCore" Version="1.0.3" />
  <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.0.2" />
  <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.0.1" />
  <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.0" />
  <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.0.1" />
  <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.0.1" />
</ItemGroup>

Save the CSProj and lets do a dotnet restore.

image

Now lets store a secret in the secret manager tools. Make sure to execute below command in context of project directory.

image

To access the stored secret in command line prompt, we can execute below command.

image

Similarly, we can remove all secret keys and values using dotnet user-secrets clear and to remove a specific key use dotnet user-secrets remove key.

To access the secret keys in MVC Core application, we need to add User Secrets in Startup class( as shown below) and add the configuration service to the project.

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();

    if (env.IsDevelopment())
    {
        builder.AddUserSecrets();
    }

    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IConfigurationRoot>(Configuration);
    services.AddMvc();            
}

Now lets try to access the user secret in Home controller as shown below.

private IConfigurationRoot _config;
public HomeController(IConfigurationRoot config)
{
    _config = config;
}

public IActionResult Index()
{
    string testConfig = _config["EmailSmtpPassword"];
    return View();
}

Run the application from VS, when we set a breakpoint and examine the secret key value, we should see below output.

image

That’s it for now. Happy Coding and Stay Tuned!!!

You may also like...