Api Key Exposure in Aspnet (Csharp)
Api Key Exposure in Aspnet with Csharp — how this specific combination creates or exposes the vulnerability
In ASP.NET applications written in C#, API keys are commonly stored in configuration files, environment variables, or injected at runtime. When these keys are accidentally exposed through logging, error messages, or insecure HTTP responses, they become a critical security risk. Because C# applications often integrate with external services using strongly-typed configuration models, developers may inadvertently serialize sensitive configuration sections or return them in debug payloads.
For example, an ASP.NET Core controller might bind configuration via IOptions<ApiSettings> and return the settings object directly in an HTTP response during development or debugging. If the ApiSettings class contains an ApiKey property and the endpoint is unintentionally exposed in production, the key is returned in clear text to any client that can trigger the endpoint. This pattern violates the principle of least privilege and can lead to unauthorized use of the key.
Additionally, C# applications that log configuration values for diagnostic purposes can expose API keys if sensitive data is not explicitly filtered. Using ILogger to log the value of an API key — even as part of an exception stack trace — results in persistent storage of the secret in logs, which may be accessible to unauthorized users or exported to monitoring systems.
The use of OpenAPI/Swagger specifications in C# projects via tools like Swashbuckle can also contribute to exposure. If the specification includes examples or default values containing real API keys, and the generated UI is accessible without authentication, any visitor can view the key directly in the browser. This occurs when c.IncludeXmlComments or custom examples inadvertently embed secrets in the documented schema.
middleBrick scans such unauthenticated attack surfaces and flags this category under Data Exposure and Unsafe Consumption checks. The scanner cross-references the OpenAPI specification against runtime behavior to detect whether API keys are returned in responses, documented in specs, or logged in application output. Findings include severity levels and remediation guidance mapped to frameworks such as OWASP API Top 10 and compliance regimes including SOC2 and GDPR.
Using the middleBrick CLI, you can run middlebrick scan <url> to detect whether your ASP.NET endpoint exposes API keys without authentication. For teams requiring deeper integration, the GitHub Action can enforce score thresholds in CI/CD pipelines, while the MCP Server enables scanning directly from AI coding assistants within development environments.
Csharp-Specific Remediation in Aspnet — concrete code fixes
To prevent API key exposure in ASP.NET applications written in C#, apply targeted code and configuration changes that ensure keys are never serialized, logged, or returned to clients.
1. Exclude sensitive properties from serialization and documentation
Use attributes to prevent API key properties from being included in JSON responses or OpenAPI documentation. In your configuration model, mark the key field with [JsonIgnore] and avoid adding example values that contain real secrets.
using System.Text.Json.Serialization;
public class ApiSettings
{
[JsonIgnore]
public string ApiKey { get; set; }
public int TimeoutInSeconds { get; set; }
}
When using Swashbuckle, suppress inclusion of the property in examples by configuring the schema filter:
services.AddSwaggerGen(c =>
{
c.SchemaFilter<OmitSensitivePropertiesSchemaFilter>();
});
public class OmitSensitivePropertiesSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (context?.Properties?.ContainsKey("ApiKey") ?? false)
{
schema.Properties.Remove("ApiKey");
}
}
}
2. Secure logging practices
Ensure that ILogger calls never include API key values. Use structured logging with explicit property exclusion or manual redaction.
var apiKey = configuration["Services:ApiKey"];
logger.LogWarning("External service call failed. Timeout: {Timeout}, ApiKeyRedacted: {Redacted}",
timeoutSeconds, "[REDACTED]");
3. Avoid returning configuration objects from endpoints
Do not bind and return configuration models directly from controllers. Instead, construct response objects that contain only necessary, non-sensitive data.
[ApiController]
[Route("api/[controller]")]
public class StatusController : ControllerBase
{
private readonly ApiSettings _settings;
public StatusController(IOptions<ApiSettings> options)
{
_settings = options.Value;
}
[HttpGet]
public IActionResult GetStatus()
{
return Ok(new { Status = "Healthy", Timeout = _settings.TimeoutInSeconds });
}
}
4. Protect configuration at rest and in transit
Store API keys using Secret Manager during development and Azure Key Vault or environment variables in production. In Program.cs, prefer configuration sources that do not persist secrets in source control.
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddUserSecrets<Program>();
var app = builder.Build();
middleBrick can validate that such configurations are not exposed by scanning your public endpoints and analyzing OpenAPI specs for unintended disclosures. Its LLM Security checks also detect prompt injection risks that could indirectly lead to key leakage in AI-integrated services.