No description
Find a file
2025-04-16 21:47:04 +02:00
README.md update readme 2025-04-16 21:47:04 +02:00

This is a guide on how to use the dotnet user secret manager, that is a little bit more concise than the official microsoft documentation on the topic.

Why secrets

  • Avoid confidential data as plain string in the code / config

  • dotnet user secret manager as an elegant way to create and access confidential data

Demo

Create Demo Worker Service

dotnet new worker -n SecretsDemo

Initiate user-secrets for that worker service

dotnet user-secrets init

Set a secret

dotnet user-secrets set "MyKey" "batman"

inject IConfiguration config to access the secret

namespace SecretsDemo;

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    IConfiguration _config;

    public Worker(ILogger<Worker> logger, IConfiguration config)
    {
        _logger = logger;
        _config = config;

        var valueFromSecretStorage = _config["MyKey"];
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
       // ...
    }
}

build project and debug through

  • dotnet build

  • F5

There's more

ms docs: set multiple secrets at once

create mysecrets.json

{
  "Some": "Secrets",
  "More": "Secrets"
}

import secrets from mysecrets.json

cat .secrets.json | dotnet user-secrets set
  • make sure to delete mysecrets.json afterwards

  • check if secrets have been set successfully

cd ~/.microsoft/usersecrets/<your-project>

User secrets in non-web applications

When in the need to read secrets from unit tests, make sure to add AddUserSecrets() to the ConfigurationBuilder:

// ...

var configuration = new ConfigurationBuilder()
            .AddUserSecrets(Assembly.GetExecutingAssembly())
            .Build();

// ...

Further Reading