C# User Secrets

Never store passwords or sensitive data in source code or configuration files. Production secrets shouldn’t be used for development or test. Secrets shouldn’t be deployed with the app. Production secrets should be accessed through a controlled means like Azure Key Vault.

Secret manager

This tool hides implementation details. The secret values are stored in a JSON file in the local machine’s user profile folder.

This tool operates on project-specific configuration settings and (!) it’s only meant for local development (!). Don’t use it for production as it’s not encrypted.

To use user secrets, run the following command in the project directory

dotnet user-secrets init

You can do this through visual studio Right click on your project inside vstudio > Administrar secretos de usuario

Set a new secret

Define an app secret containing a key > value

dotnet user-secrets set "OpenAI:ApiKey" "sk-xxxx"

Read a secret

var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddUserSecrets<Program>();
string openAiKey = builder.Configuration["OpenAI:ApiKey"];

Read a secret - using DI

public class IndexModel(IConfiguration _config) : PageModel
{
	public void OnGet()
	{
		var openAiKey = _config["OpenAI:ApiKey"];
	}
}

Delete a secret

dotnet user-secrets remove "OpenAI:ApiKey"

Reference(s)

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