226 words
1 minutes
Dotnet user-secrets
2023-04-14
2025-08-19

Don’t store secrets in your configs!
Even locally on your dev machine there are options.
In .NET you can replace a setting in appsettings.json with a secret from the “secrets store”.
The dotnet CLI has commands for managing these secrets.

Using the dotnet user-secrets CLI#

From the project directory - initiate the secret storage with the command:

dotnet user-secrets init

This will add a <UserSecretsId> element to your .csproj file:

<PropertyGroup>
  <TargetFramework>net9.0</TargetFramework>
  <Nullable>enable</Nullable>
  <EnableNETAnalyzers>true</EnableNETAnalyzers>
  <UserSecretsId>c7dafe55-cb55-4076-b446-f13299741441</UserSecretsId>
</PropertyGroup>

To add a secret to the user store, run the following command from the project folder:

dotnet user-secrets set "ThePath:ToTheSecret:InAppsettingsJson" "secretgoeshere"

This will create a folder with the same name as the <UserSecretsId> in the user’s profile directory. In this directory a secrets.json file will be created, which will contain the secrets in a JSON format.

The path to the JSON file would be:
C:\Users\%username%\AppData\Roaming\Microsoft\UserSecrets\c7dafe55-cb55-4076-b446-f13299741441\secrets.json

And the content of the file would be:

{
  "ThePath:ToTheSecret:InAppsettingsJson": "secretgoeshere"
}

Note that the secret is stored in clear text, so it’s not a secure storage. However, this ensures that the secret is not checked into source control.

Further the secrets can be listed with the command:

dotnet user-secrets list

And removed with the command:

dotnet user-secrets remove "ThePath:ToTheSecret:InAppsettingsJson"

Or completely wiped with:

dotnet user-secrets clear

Mapping the secrets to the appsettings.json configuration#

In your Program.cs you must add a call to AddUserSecrets() to load the user secrets:

    public static IHostBuilder CreateWebHostBuilder(string[] args) =>
      Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            if (hostingContext.HostingEnvironment.IsDevelopment())
                config.AddUserSecrets<Startup>();
        });

References:
https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-9.0&tabs=windows

Dotnet user-secrets
https://cognitiveoverload.blog/posts/dotnet/dotnet-user-secrets/
Author
cognitive;overload
Published at
2023-04-14
License
CC BY