Genarally, we need to include some sensitive data in our appsettings.json file, like a connection string that content a username and password or a something kind of private key:
{
"ConnectionStrings": {
"MongoDb": "mongodb://mongoadmin:secret@127.0.0.1:27017/aurora/?authSource=admin"
}
}
However, the exposure of these credentials is not safe and is not a good practice either. And, when a developer get your repository, maybe they need to do adjust your docker images or change the sensitive data/connection strings to attend the project.
Let's see how can we solve this! 🤓
User Secrets
This is a way that allows us to manage sensitive data for .NET on local development.
So, to configure it in your project, you'll need something like below in your Startup/Program class:
WebApplication
.CreateBuilder(args)
.Host
.ConfigureAppConfiguration((context, configurationBuilder) =>
{
configurationBuilder
.AddUserSecrets(Assembly.GetExecutingAssembly())
.AddEnvironmentVariables();
})
Now, we need to configure our secrets, right?
First, let's open the startup project folder and, next open the terminal, and follow the commands below:
To enable secret storage:
dotnet user-secrets init
To add a secret:
dotnet user-secrets set "ConnectionStrings:MongoDb" "[YOUR CONNECTION]"
To add a secret in a list:
dotnet user-secrets set "PrivateKey[0]" "[YOUR KEY]"
dotnet user-secrets set "PrivateKey[1]" "[YOUR KEY]"
To list the secrets:
dotnet user-secrets list
To remove a secret:
dotnet user-secrets remove "ConnectionStrings:MongoDB"
Conclusion
- Never store passwords or other sensitive data in source code
- Production/Staging/Development should not be used for local test/development
- Sensitive data should not be deployed with the app
- You should store sensitive data in a protected environment/tool, like Azure Key Vault
Top comments (0)