When developing an application, we sometimes need to call an api or connect to a database and for this, we use passwords or keys to connect. If we put them in the appsettings, there’s always the danger of forgetting about them and commit them to source control which can then cause a security flaw.
To prevent this, dotnet provides us with a very useful command to safely store our secrets where they won’t be accidentally committed.
- First open a command line in your solution folder
- Execute this command :
dotnet user-secrets init
This command initialises the local secret repository of your solution
- To store data, use this command
dotnet user-secrets set "keyname" "keyvalue"
Now we can easily access it from our Console application without risking this secret to leak or end up in the wrong hands.
- You need to install the following nuget Packages into your solution
- In your Program.cs file you will need a ConfigurationBuilder and tie the Id you received from the init command you ran before to the builder
var builder = new ConfigurationBuilder();
- After a call to the buillder.Build() method you can now access your secret
var configuration = builder.Build();
var secret = configuration["Secret"];