.NET Aspire makes it easier to configure distributed applications by defining services, databases, caches, and other resources in an AppHost project. Developers can use resource references, parameters, and environment variables to provide configuration to different application components.
However, configuration management becomes a security concern when an application moves from local development to staging or production. Database passwords, API keys, access tokens, storage credentials, and other sensitive values must not be stored in source code or exposed through deployment files.
A configuration approach that works for local development may not be suitable for production. For example, a developer might use a local database password stored in User Secrets, while a production application should retrieve its credentials from a secure secret provider.
.NET Aspire provides external parameters that help model values supplied from outside the application. These parameters can represent secrets, connection strings, and other environment-specific settings.
In this article, we will explore how to keep sensitive configuration out of production source code, use Aspire secret parameters, integrate Azure Key Vault, and avoid common security mistakes when deploying distributed .NET applications.
Understanding Configuration and Secrets in Aspire
Before implementing secret management, it is important to understand the difference between ordinary application configuration and sensitive information.
Application configuration includes values such as:
- Application environment.
- Logging levels.
- Feature flags.
- Pagination limits.
- Service endpoint names.
- Retry policies.
Secrets include values such as:
- Database passwords.
- Third-party API keys.
- Storage account credentials.
- OAuth client secrets.
- Private access tokens.
- Signing keys.
These values should not be handled in the same way.
For example, a logging level can safely appear in appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information"
}
}
}
However, placing a production database password in the same file creates a security risk.
{
"ConnectionStrings": {
"DefaultConnection": "Host=production-db;Username=admin;Password=ProductionPassword123"
}
}
If this file is committed to source control, anyone with access to the repository may obtain the credentials.
The recommended approach is to keep ordinary configuration in application settings files and obtain sensitive values from an appropriate secret-management system.
Using Aspire External Parameters for Secrets
Aspire provides the AddParameter method to define values that are supplied externally.
You can mark a parameter as secret by setting secret to true.
Consider an application that uses PostgreSQL and an ASP.NET Core API.
The AppHost can define a database password parameter and pass it to the PostgreSQL resource:
var builder = DistributedApplication.CreateBuilder(args);
var dbPassword = builder.AddParameter(
"db-password",
secret: true);
var postgres = builder.AddPostgres(
"postgres",
password: dbPassword)
.WithDataVolume();
var database = postgres.AddDatabase("catalog");
builder.AddProject<Projects.Catalog_Api>("catalog-api")
.WithReference(database)
.WaitFor(database);
builder.Build().Run();
Here, the database password is not written directly into the AppHost source code.
The parameter is marked as secret, allowing Aspire's deployment tooling to treat it as sensitive information.
The database resource receives the parameter as its password. The API receives its database connection information through the resource reference.
This is preferable to manually constructing a connection string containing a password and repeating it across multiple projects.
One important point is that secret: true does not encrypt a value by itself or turn Aspire into a secret vault. It identifies the parameter as sensitive so that the relevant tooling and deployment target can handle it appropriately. The actual value must still come from a secure configuration source.
Storing Local Development Secrets
Developers need credentials when running an Aspire application locally. However, those credentials should not be committed to the repository.
.NET User Secrets provides a convenient solution for local development.
First, initialize User Secrets in the AppHost project:
dotnet user-secrets init --project Catalog.AppHost
Then store the database password:
dotnet user-secrets set "Parameters:db-password" "local-development-password" --project Catalog.AppHost
Aspire can resolve the parameter from the AppHost configuration.
The value remains outside the project directory and is not committed through the normal source-control workflow.
For example, the AppHost project can use the following structure:
Catalog.AppHost/
│
├── Program.cs
├── appsettings.json
├── appsettings.Development.json
└── Catalog.AppHost.csproj
The configuration files can contain non-sensitive application settings, while the local database password remains in User Secrets.
Do not put production credentials into local development secrets. Development, testing, staging, and production should use separate credentials with separate access permissions.
Passing Secrets to Application Resources
Sometimes an application needs a secret that is not related to an infrastructure connection string.
For example, a .NET service may need an external payment provider API key.
You can define another secret parameter in the AppHost and pass it to the application as an environment variable.
var builder = DistributedApplication.CreateBuilder(args);
var paymentApiKey = builder.AddParameter(
"payment-api-key",
secret: true);
builder.AddProject<Projects.Payment_Api>("payment-api")
.WithEnvironment("Payment__ApiKey", paymentApiKey);
builder.Build().Run();
Inside the Payment API, read the value through the standard configuration system:
var builder = WebApplication.CreateBuilder(args);
var paymentApiKey =
builder.Configuration["Payment:ApiKey"];
if (string.IsNullOrWhiteSpace(paymentApiKey))
{
throw new InvalidOperationException(
"Payment API key is not configured.");
}
var app = builder.Build();
app.Run();
The environment variable Payment__ApiKey maps to the hierarchical configuration key Payment:ApiKey.
This approach keeps the secret value out of the application source code.
However, environment variables should not automatically be considered secure storage. They can be exposed through process inspection, diagnostic tools, container metadata, or insufficiently protected operational systems.
For sensitive production credentials, prefer a secure secret provider or identity-based authentication when supported.
Using Azure Key Vault for Production Secrets
For applications deployed in Azure, Azure Key Vault provides a centralized service for storing and managing secrets.
Instead of placing production API keys and passwords in application settings files, an application can retrieve them from Key Vault using an authenticated identity.
To use the Azure Key Vault configuration provider, install the required packages:
dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
dotnet add package Azure.Identity
Configure Key Vault in the application:
using Azure.Identity;
var builder = WebApplication.CreateBuilder(args);
var keyVaultUri =
builder.Configuration["KeyVault:VaultUri"];
if (!string.IsNullOrWhiteSpace(keyVaultUri))
{
builder.Configuration.AddAzureKeyVault(
new Uri(keyVaultUri),
new DefaultAzureCredential());
}
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
The KeyVault:VaultUri value is an ordinary configuration value containing the vault endpoint, not a secret.
The application uses DefaultAzureCredential to authenticate. During local development, this may use an available developer credential, such as Azure CLI or Visual Studio authentication. When deployed to a supported Azure environment, it can use the application's managed identity.
Suppose Key Vault contains a secret named Payment--ApiKey.
The double dash is used to represent the configuration hierarchy separator. The provider maps this secret to Payment:ApiKey.
The application can retrieve the value through the standard configuration system:
var paymentApiKey =
builder.Configuration["Payment:ApiKey"];
The application does not need to know how the secret is stored or retrieved.
This makes it easier to move between local development and production without changing the business logic.
For production deployments, assign the application's managed identity only the permissions it needs to read the required secrets. Avoid giving every service access to the entire vault.
Using Managed Identity Instead of Storing Credentials
Secret management is important, but avoiding long-lived credentials is even better when the infrastructure supports identity-based authentication.
For example, an application running in Azure can use a managed identity to authenticate with supported Azure services.
Instead of storing a storage account access key, the application can obtain an identity token and use it to access the storage account.
The application can use DefaultAzureCredential:
using Azure.Identity;
using Azure.Storage.Blobs;
var credential = new DefaultAzureCredential();
var blobServiceClient = new BlobServiceClient(
new Uri("https://mystorageaccount.blob.core.windows.net"),
credential);
The application authenticates using its available identity.
In production, configure a managed identity for the hosting resource and grant it the required data-plane permissions.
This removes the need to store a storage account key in application configuration.
The same principle applies to other supported services. Prefer managed identities, workload identities, or other short-lived authentication mechanisms over long-lived passwords and client secrets whenever possible.
Separating Development and Production Configuration
A production application should not depend on the same credentials used during local development.
A useful configuration strategy is:
| Environment |
Configuration approach |
Secret source |
| Local development |
appsettings.json and environment variables |
User Secrets |
| Automated testing |
Test configuration and isolated resources |
CI/CD secret store |
| Staging |
Deployment-specific configuration |
Key Vault or another secure provider |
| Production |
Environment-specific application configuration |
Managed identity and secure secret provider |
For example, an AppHost can define an external parameter:
var builder = DistributedApplication.CreateBuilder(args);
var paymentApiKey = builder.AddParameter(
"payment-api-key",
secret: true);
builder.AddProject<Projects.Payment_Api>("payment-api")
.WithEnvironment("Payment__ApiKey", paymentApiKey);
builder.Build().Run();
The parameter value can be supplied through different sources depending on the environment.
For local development, use User Secrets. For deployment, provide the value through the deployment pipeline or an appropriate secure provider.
Aspire supports parameter resolution through standard configuration sources, including environment variables. For example, a deployment pipeline can provide a parameter using an environment variable named Parameters__payment-api-key.
The exact secure storage and injection mechanism depends on the deployment target.
Also remember that the AppHost environment does not automatically configure every child resource's ASP.NET Core environment. Set the appropriate environment configuration on application resources when needed.
Protecting Secrets in CI/CD Pipelines
Deployment pipelines are another important area where secrets can accidentally become exposed.
For example, a GitHub Actions workflow may need a database password or payment provider API key during deployment.
Avoid writing the actual values directly into workflow files.
Instead, store them in the CI/CD platform's protected secret store and pass them to the deployment process.
A simplified GitHub Actions example is:
name: Deploy Aspire Application
on:
workflow_dispatch:
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '10.0.x'
- name: Deploy application
run: aspire deploy --environment Production
env:
Parameters__payment-api-key: ${{ secrets.PAYMENT_API_KEY }}
This example demonstrates passing a secret parameter to the Aspire deployment process. The actual deployment target must also support the required parameter resolution and secure storage behavior.
Do not print environment variables or secret values in pipeline logs. Avoid commands that display complete configuration files containing credentials.
For production workloads running in Azure, workload identity federation can also reduce the need for long-lived service principal credentials in CI/CD systems.
Preventing Secret Exposure Through Logs and Diagnostics
Even when secrets are stored securely, applications can accidentally expose them during execution.
For example, consider this debugging statement:
logger.LogInformation(
"Using database connection: {ConnectionString}",
connectionString);
If the connection string contains a username and password, this log entry exposes sensitive information.
Instead, log safe information:
logger.LogInformation(
"Database connection configuration loaded successfully.");
The same rule applies to API keys, access tokens, authentication headers, and payment credentials.
When troubleshooting Aspire applications, developers should inspect resource logs, environment configuration, and distributed traces without exposing secret values.
Use redaction where appropriate and restrict access to dashboards, telemetry systems, and deployment logs.
Common Mistakes in Aspire Secret Management
| Mistake |
Why it is risky |
Recommended approach |
| Storing production passwords in appsettings.json |
Credentials can be committed to source control |
Use a secure secret provider |
| Hardcoding secrets in AppHost |
Sensitive values become part of source code |
Use external parameters |
| Assuming secret: true encrypts values |
It is a sensitivity declaration, not a secret store |
Provide values through secure storage |
| Reusing development credentials in production |
Increases the impact of credential exposure |
Use separate credentials per environment |
| Passing secrets through ordinary environment variables without protection |
Process and diagnostic access may expose them |
Prefer secure provider or identity-based access |
| Logging connection strings |
Credentials may appear in centralized logs |
Log safe configuration metadata |
| Giving every service access to all secrets |
Increases the attack surface |
Apply least-privilege access |
| Never rotating credentials |
Compromised credentials may remain valid |
Establish a rotation process |
Best Practices for Production Aspire Applications
When designing a secure configuration strategy, follow these practices:
- Keep secrets out of source code and committed configuration files.
- Use Aspire external parameters for values that must be supplied to resources.
- Mark sensitive parameters with secret: true.
- Use User Secrets for local development rather than production credentials.
- Store production secrets in a dedicated secret-management system.
- Prefer managed identity or workload identity over long-lived credentials.
- Apply least-privilege permissions to services and deployment identities.
- Keep development, testing, staging, and production credentials separate.
- Avoid logging complete connection strings, tokens, or API keys.
- Rotate credentials regularly and revoke compromised credentials immediately.
- Review CI/CD logs and deployment artifacts for accidental secret exposure.
Advantages and Disadvantages
Using Aspire external parameters and secure configuration providers offers several advantages:
- Sensitive values remain outside application source code.
- Different environments can use different credentials.
- Shared infrastructure credentials can be managed centrally.
- Deployment pipelines can supply configuration without modifying application code.
- Managed identities can reduce dependency on long-lived credentials.
- Services can retrieve configuration through the standard .NET configuration system.
There are also some considerations:
- Secure secret storage requires additional infrastructure and permissions.
- Applications need appropriate authentication to access secret providers.
- Environment variables can still expose sensitive values if the runtime is not protected.
- Secret rotation requires coordination with applications and dependent services.
- Incorrect parameter configuration can prevent resources from starting.
- Developers must understand the difference between marking a value as secret and actually storing it securely.
Summary
Keeping Aspire configuration out of production secrets requires a clear separation between ordinary application settings and sensitive credentials.
Use Aspire external parameters to represent values supplied from outside the application. Mark sensitive parameters with secret: true and store local development values in User Secrets. For production, use a dedicated secret-management system such as Azure Key Vault, and prefer managed identities or other short-lived authentication mechanisms whenever possible.
Also protect deployment pipelines, logs, environment variables, and diagnostic systems because secrets can leak even when their original storage location is secure.
A secure Aspire application does not depend on hardcoded passwords or committed configuration files. It obtains the required values through controlled configuration sources, uses only the permissions it needs, and keeps sensitive information out of application code and operational logs.
Join the conversation! Your thoughts help the community grow.