Never Store Secrets in appsettings.json

You’ve probably seen some security illiterate do this before.

You see what I mean? The secret on line 4 which will be committed to your code repo.


The person who’d do this is basically anyone new to ASP.NET Core. It’s understandable why something like this happens. It’s easy. It makes your development experience pleasant.


However, it’s a massive security flaw. Never store sensitive data in source code.


The slightly more experienced developer would probably make an appsettings.Development.json. This isn’t any better unless you actually .gitignore that file.
Hide your secrets!

Luckily, there’s an easy fix to this issue.

Don’t make an additional appsettings.SomeEnvironment.json. Instead, just use the default appsettings.json as a template for what’s required by the application to function.

You see? Line 4, no secret provided.
    

Okay, now we’ve removed the issue from our file. Let’s figure out how to populate the ConnectionStrings:default, in a secure manner.

In the terminal at the project location, write dotnet user-secrets init. A UserSecretsId is generated and stored in your .csproj file.

Next, it’s as simple as writing dotnet user-secrets set "ConnectionStrings:default" "my_connectionstring”

That’s it. You no longer mistakenly have sensitive data in your source code.
What to do in production, you may ask

In production, you’d need to have an appsettings.json with all the sensitive data in it — or, you can just add them as environment variables.

An even better approach is to use a KeyVault, like Azure KeyVault. It’s easy. It’s secure. There’s no excuse not to use it. But setting a KeyVault up is beyond the scope of this article.
Post a Comment