I have seen similar questions on SO, but no answers or examples of how to do it. According to MS DOCS https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-3.1&tabs=windows it should be possible to store secrets in environment variables when deploying to staging and/or production environments.
When I am working in development mode, then I use the dotnet user-secrets CLI, which generates a secrets.json, and works perfectly fine while in development mode.
The headache is once I leave development mode, and setting the ASPNETCORE_ENVIRONMENT to Production. I cannot figure out how to use the same key-tag in my code, without creating some custom.
For exaple, in my code I refer to the secret using a key name: "My:Secrets:ClientSecret" (in secrets.json represented as:
{
"My:Secrets:ClientSecret": "SomeSecretValueInHere"
}
So when I in my .net 6 code, refer to this key in configuration by the following example:
var clientSecret = Configuration["My:Secrets:ClientSecret"];
It works while in development as they are stored using secrets.json, but if I build to Production, and having a "My:Secrets:ClientSecret" (also tried to replce the : with double underscore __ without any differences), stored my System variables with the value "SomeSecretValueInHere", then the clientSecret variable in my .net 6 code is left empty.
Could anyone please provide an example of how to do this? I don't have access to using secrets managers like AzureKeyVault or similar, and I would really try to avoid creating custom code saying pseudo
if(Environment.IsDevelopment)
UseUserSecret
else
LoadEnvironmentVariablesInSomeWay
Using the following builder to create the configuration in code:
var builder = WebApplication.CreateBuilder(args)
.Configuration.AddEnvironmentVariables()
.AddUserSecrets(Assembly.GetExecutingAssembly(), true);
CodePudding user response:
As described in the docs if you have environment variables included n configuration sources (for example as done in the default setup) then Configuration["My:Secrets:ClientSecret"]
will be read from My__Secrets__ClientSecret
environment variable (unless My:Secrets:ClientSecret
from earlier config source in the pipeline as for example from CLI args in the default setup) i.e. should be the same as Environment.GetEnvironmentVariable("My__Secrets__ClientSecret");
.
Note that based on how and on which OS the environment variable is set up you might need to reboot/log out or start the app from the same terminal where you set the variable.