How to Securely Manage API Keys and Secrets in .NET Using User Secrets

In this tutorial, we will learn how to hide API secrets in .NET.

To hide secrets from being exposed first in your CLI execute the following command:-

Run the following command from the directory in which the project file exists:

dotnet user-secrets init

Then write the following code in the console to create secret data:

dotnet user-secrets set "Movies:ServiceApiKey" "12345"

To remove the secret key you can use the following command:

dotnet user-secrets remove "Movies:ConnectionString"

To list secret keys:

dotnet user-secrets list

To clear all secret keys:

dotnet user-secrets clear

Now configure Program.cs to use secret keys:

var builder = WebApplication.CreateBuilder(args);
var movieApiKey = builder.Configuration["Movies:ServiceApiKey"];

var app = builder.Build();

app.MapGet("/", () => movieApiKey);

app.Run();

Read the secret key in your file using IConfiguration:

public class IndexModel : PageModel
{
    private readonly IConfiguration _config;

    public IndexModel(IConfiguration config)
    {
        _config = config;
    }

    public void OnGet()
    {
        var moviesApiKey = _config["Movies:ServiceApiKey"];

        // call Movies service with the API key
    }
}

Additional Notes
- User Secrets are only for local development and are not meant for production. For production secrets, consider using services like Azure Key Vault or environment variables.
- User Secrets store data on your local machine outside the project folder, so secrets don’t get pushed to source control (like GitHub).

Conclusion
Using User Secrets in .NET helps keep sensitive information safe during development and prevents accidental leaks of API keys or connection strings. It’s an easy step towards more secure coding practices.

For detailed information visit this page: Microsoft Docs - Manage app secrets in development

Comments