How to add and use user secrets to a .NET Core Console App
You’ve probably spent the past 9 hours looking at examples of adding user secrets to your project just to be left with the same thought as me…
“That’s cool but how do I do it for a console app”
It’s all well and good if you are adding secrets to an API project just right click and boom visual studio does all the magic for you.
But when it comes to a console app VS chooses the wrong card in this trick.
Not to worry though, I’m here to help you.
Step One
Right click your project.
Then click edit <insertProjectName>.csproj
Step Two
Add in the following line underneath TargetFramework:
<UserSecretsId>Insert New Guid Here</UserSecretsId>
Keep a note of this Guid you will need it later as your userSecretsId.
And then within Item Group with your Nuget Packages add the following line:
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0"/>
Step Three
Crack open a cold PowerShell (Admin) and cd into the directory of your console app
Then stick in the following line:
dotnet user-secrets
This will open up the help section of user secrets, take a moment to look around.
To add a user secret insert the following line:
dotnet user-secrets set YourSecretName "YourSecretContent"
To edit a secret just do the exact same but with the new content, it will override the previous secret.
This will create a secret in secrets.json, this can be found here:
%APPDATA%\microsoft\UserSecrets\<userSecretsId>\secrets.json
userSecretsId is the Guid that you used previously in your .csproj file
Step Four
Now this step is a bit of a hack…
Who doesn’t love a good hack.
Open up secrets.json and add the following
{
"YourClassName":{
"Secret1":"The Earth Is Flat",
"Secret2":"Pythagoras is a liar"
}
}
This then allows you to create a class in your project to access the secrets.
Step Five
The final step…Hopefully you are still here
Within your project add this Nuget Package
Microsoft.Extensions.Configuration.UserSecrets
Then make your Program.cs look similar to the following:
You will notice above a block of code concerning environment. Within console apps in .NET core there is no concept of working environment i.e. production, development.
We have to mock this. This can be done by adding environmental variable that determines the current working environment.
You should at the moment only use user secrets in a development environment as they are just stored in unencrypted JSON on your local machine. The main use of them is to prevent passwords and the like being committed to source control. In production I would recommend using something like Azure Key Vault.
You can then access these secrets by injecting IOptions<NameOfSecretsClass> into the constructor of your class
You can then use these secrets by doing the following:
_secrets.Secret1;
Simples right…
So far I have only tested this with basic strings but I imagine it should work with whatever you want to throw at it.