Safely store secrets during development

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.

  1. First open a command line in your solution folder
  2. Execute this command :
    dotnet user-secrets init
    This command initialises the local secret repository of your solution
  3. 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.

  1. You need to install the following nuget Packages into your solution
  2. 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();
  3. After a call to the buillder.Build() method you can now access your secret
    var configuration = builder.Build();
    var secret = configuration["Secret"];

Happy coding

Leave a Reply

Your email address will not be published. Required fields are marked *