How to use ASP.NET with SecretHub
This guide will show how you to load secrets from SecretHub into your ASP.NET application. These could be database passwords, API keys, encryption keys, or anything else you’d like to keep secret.
Instead of putting secrets values in source code or config files, you’ll be able to load them on demand from a secure and central place.
Before you begin
Before you start using SecretHub with ASP.NET, make sure you have completed the following steps:
- Set up SecretHub on your workstation.
- Install .NET and have a project ready to use.
Step 1: Replace plaintext values with references
Collect all secrets from your source code,
appsettings.json or other config files, and use the SecretHub CLI to encrypt and store them.
To do this, copy the values to your clipboard and use the
write command and specify a path on SecretHub:
secrethub write --clip your-username/demo/api_key
In your app launch script or runtime environment, you can configure the secrets your app needs as environment variables.
But instead of using plaintext values, reference the secrets by the path you’ve chosen earlier, prefixed with
Step 2: Load secrets into your app
To load secrets into your app, there’s multiple options you can choose from.
To keep your application code SecretHub-agnostic, you can use the CLI to load secrets into environment variables.
Simply wrap your app start command with
secrethub run and any environment variable that references a SecretHub secret will get updated to contain the actual secret value:
secrethub run -- dotnet run
In your C# code, you can simply read the secrets from the environment:
using System; // ... string apiKey = Environment.GetEnvironmentVariable("API_KEY");
As an added bonus,
secrethub run keeps an eye on your log output to see if any secret accidentally gets logged and masks them from the output!
You can also choose to include the SecretHub .NET SDK directly into your application code base. This is especially useful in situations where you don’t control the runtime environment (e.g. Azure App Service, AWS Lambda, Google Cloud Functions).
The .NET SDK can be found on the NuGet Gallery, so you can add it as a dependency to your app in the way you’re used to:
dotnet add package SecretHub
In your C# code, you can create a SecretHub
Client and use the
ResolveEnv function to automatically replace every secret reference present in the environment variables:
var secrets = new SecretHub.Client().ResolveEnv(); string apiKey = secrets["API_KEY"];
That’s it! You have now provisioned the app without a secret being near it. 🎉
Next Up: Deploy your app
It’s great if simple examples work locally, but they don’t mean much if they don’t work anymore in a real-world scenario. So to read more about actually deploying your app with SecretHub, see: