Course contentsShow
← C#
Lesson 1194 of 1,90811. Identity, Security, and ClaimsFree lesson

Managing Sensitive User Secrets

Securely handle API keys and secrets associated with identity providers.

In this lesson, you will learn how to protect sensitive credentials—like API keys or OAuth client secrets—from being accidentally exposed in your source code or version control system.

The Problem with Hard-Coding

When integrating external identity providers or managing service-to-service communication, you often need "secrets." If you hard-code these strings directly into your C# classes or appsettings.json files, they become visible to anyone with access to your repository. This is a critical security vulnerability, especially if your code is hosted on platforms like GitHub.

Using User Secrets for Development

During local development, ASP.NET Core provides a tool called the Secret Manager. It stores your sensitive configuration data in a JSON file located in your local user profile folder, which is outside your project directory and never committed to source control.

To use this, right-click your project in Visual Studio and select "Manage User Secrets." This opens a secrets.json file where you can store your credentials:

{
  "ExternalProviders": {
    "Google": {
      "ClientSecret": "your-super-secret-key-here"
    }
  }
}

In your application code, you access these values using the standard IConfiguration interface, just as if they were in your appsettings.json:

var clientSecret = Configuration["ExternalProviders:Google:ClientSecret"];

Production Considerations

While secrets.json is perfect for your local machine, it is not used in production. When deploying to environments like Azure, you should inject these values using secure Key Vaults or environment variables. The beauty of the IConfiguration system is that it treats these production secrets exactly like the local ones; your C# logic remains clean and oblivious to where the secrets are actually stored.

By abstracting secret retrieval through the configuration provider pattern, you ensure that your code remains portable and secure, regardless of the environment it runs in. Never check a secret into your repository; always treat them as external dependencies that are "injected" at runtime.

Key Takeaway: Never store raw secrets in source control; use the Secret Manager for local development and secure environment-specific configuration providers for production deployment.