Before the release of .NET Core, developers used to store keys, connection strings, and other secrets in application configuration files. .NET Core provides a wide range of storage options to store this information and developers are only restricted to storing this information in web.config files, and now the information can be stored in JSON-based appsettings.json files, XML-based configuration files, or environment variables, and so on. Sometimes, when there is a big team and multiple developers are working on the same project, we don't want those keys to be shared among them. A good example is an e-mail gateway where developers use a third-party gateway such as Google, Hotmail, or Yahoo and use their login credentials to test it out.
.NET Core provides a Secret Manager Tool to store application secrets. It protects the values by storing them in a separate JSON file on the following path, which differs for each OS (operating system).
Windows: %APPDATA%microsoftUserSecrets<userSecretsId>secrets.json
Linux: ~/.microsoft/usersecrets/<userSecretsId>/secrets.json
Mac: ~/.microsoft/usersecrets/<userSecretsId>/secrets.json
Secret Manager Tool can be used by adding the following NuGet package:
Microsoft.Extensions.SecretManager.Tools
It also requires the userSecretsId, which should be unique for each project running on that machine. The userSecretsId can be added as follows:
"userSecretsId": "aspnet-UserSecretSample-c5c2838b-7727
-4242-9973-d2b79c40e636",
Finally, we can set up a builder and add user secrets by calling the AddUserSecrets method as follows:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder();
if (env.IsDevelopment())
{
builder.AddUserSecrets();
}
}
public IConfigurationRoot Configuration { get; }
This also requires the following package to be added to your project:
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0"