User Sercets using the Secret Manager in ASP.NET Core

yawo
December 1, 2023

The Secret Manager tool manages configuration settings specific to a project and stores them in your user profile.

Using Visual Studio:

Right-click on you project and Select "Manage User Secrets". A secrets.json file will open and can be used to store you configruation. You can then add your key:value configuration and read them using the Asp.Net Core Configuration API. When you open your project file (double-click project folder in VS), a UserSecretsId element in inserted into the PropertyGroup section, with a unique value.

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <InvariantGlobalization>true</InvariantGlobalization>
    <UserSecretsId>d709cdcb-a3b2-4faa-9485-c7f621c42f38</UserSecretsId>
  </PropertyGroup>

</Project>

Using .NET CLI

Using the command line, navigate to your project directory and run the following:

dotnet user-secrets init


The command above inserts a UserSecretsId element into the PropertyGroup section of the project file. By default, this UserSecretsId contains a GUID as its inner text. The text itself is arbitrary, yet specific to the project, ensuring uniqueness.

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <InvariantGlobalization>true</InvariantGlobalization>
    <UserSecretsId>d709cdcb-a3b2-4faa-9485-c7f621c42f38</UserSecretsId>
  </PropertyGroup>

</Project>

Then you can set a secret:

dotnet user-secrets set "PublicURL" "https://example.com"
dotnet user-secrets set "SomeObject:SomeProperty" "value"

To remove a secret:

dotnet user-secrets remove "PublicURL"

References:

https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-8.0&tabs=windows#secret-manager