User secrets keep development-time configuration values outside a project and its source repository. They are useful for connection strings and authentication keys that differ between developers or environments. Avoid putting those values in appsettings.json when committing that file would expose them. section 13.5
Set up Secret Manager from the project directory:
- Run `dotnet user-secrets init`. This adds a `UserSecretsId` GUID to the project file. The GUID can be committed; it identifies a secrets file stored on each developer’s machine, not a shared set of values. section 9.4.2
- Run `dotnet user-secrets set "CosmosDbSettings:AuthKey" "12345"` to add or update a value. The colon identifies a nested configuration key. section 13.5
- Read the value through configuration rather than embedding it in application code. For a connection string stored as `ConnectionStrings:Catalog`, call `config.GetConnectionString("Catalog")` when configuring the database context. section 9.4.2
Listing 9.14 Getting connection string from secret through configuration
var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration; #1
builder.Services.AddDbContext<CatalogContext>(options =>
{
var connStr = config.GetConnectionString("Catalog"); #2
options.UseSqlite(connStr);
});
The database registration obtains its connection string from configuration and passes it to `UseSqlite`; the consuming code does not need to know where the value was stored. section 9.4.2
The secrets file is local JSON. On Windows it resides under `%APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json`; on Linux and macOS, under `~/.microsoft/usersecrets/<user_secrets_id>/secrets.json`. After configuration sources are combined, a locally supplied `CosmosDbSettings:AuthKey` can join other values in the same settings section. section 13.5
Use user secrets for local development, not as the container’s production secret-delivery mechanism. A container can instead load an optional `/settings/secrets.json` configuration file and bind its `CosmosDbSettings` section. Environment variables are another delivery option, but cluster maintainers may be able to view them. section 13.5
Listing 13.24 Adding optional file configuration source
builder.Configuration.AddJsonFile(
"/settings/secrets.json", #1
optional: true); #2
builder.Services.Configure<CosmosDbSettings>( #3
builder.Configuration.GetSection("CosmosDbSettings"));
var app = builder.Build();
The optional file source illustrates a container-oriented configuration path separate from each developer’s local user-secrets file. section 13.5
Client and tenant IDs for Azure AD authentication can also go in user secrets when they vary by developer or environment, even if the IDs are not themselves secret. section 9.5.2

