HIGH api key exposureaspnetbearer tokens

Api Key Exposure in Aspnet with Bearer Tokens

Api Key Exposure in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability

In ASP.NET applications, bearer tokens are commonly transmitted via the Authorization header as Bearer {token}. When API keys are embedded in client-side code, configuration files with overly broad access, or logged inadvertently, they can be exposed through this channel. Because bearer tokens are often long-lived and stored in a single location (e.g., a static string or configuration provider), a single leak can expose the entire key. This risk is amplified when applications use the same token across multiple environments or services, and when debug endpoints or error pages inadvertently surface the Authorization header in logs or responses.

ASP.NET’s default behavior around authentication can inadvertently contribute to exposure. For instance, if an endpoint does not explicitly restrict which HTTP methods or origins are allowed, an attacker may probe for misconfigured CORS or use client-side JavaScript to trigger requests that include the Authorization header. In addition, if the application uses cookie-based authentication alongside bearer schemes without clear separation, a token intended for API access might be sent to a browser context where it is accessible via JavaScript or logs. MiddleBrick scans detect such exposure by checking whether the Authorization header is transmitted over unauthenticated endpoints and whether sensitive patterns appear in responses, helping to identify scenarios where a bearer token could be leaked.

Another vector involves improper host or header validation. If an ASP.NET application reflects the Authorization header in error messages, logs, or telemetry, a bearer token may be written to application logs or exposed through SSRF-induced external requests. For example, an attacker who can control a URL parameter might trigger an outbound request that includes the token in plaintext to an external service. The framework’s configuration of authentication schemes and the way tokens are passed to HTTP clients are critical: using hardcoded strings, failing to rotate keys, or storing them in insecure configuration sections increases the likelihood of exposure. MiddleBrick’s checks for data exposure and unsafe consumption help surface these patterns by correlating runtime behavior with the declared authentication mechanisms in OpenAPI specs.

OpenAPI/Swagger analysis plays a role in identifying mismatches between declared security schemes and actual runtime behavior. When a spec defines a bearer token requirement but the implementation allows unauthenticated access to endpoints that return sensitive data, the gap can lead to inadvertent token exposure through error responses or metadata endpoints. MiddleBrick resolves $ref definitions across 2.0, 3.0, and 3.1 specs to cross-reference where bearer tokens should be required and compares that with what the live endpoints accept. This highlights cases where an API key or bearer token is effectively exposed due to missing security requirements or overly permissive CORS and header handling.

LLM/AI Security checks add another layer of detection for token leakage in model outputs. If an endpoint that uses bearer tokens also interacts with external services or logs user input, there is a risk that the token appears in generated text or error traces. MiddleBrick’s system prompt leakage patterns and output scanning look for token-like strings in responses, ensuring that bearer tokens do not inadvertently become part of loggable or returned data. By combining runtime analysis with spec validation and AI-specific probes, the scanner identifies subtle exposure paths that are difficult to catch with manual review alone.

Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes

Remediation focuses on strict handling of bearer tokens, minimizing their exposure surface, and ensuring proper validation at every layer. In ASP.NET, prefer configuration-based storage over hardcoded strings and avoid echoing the Authorization header in responses or logs. Use the built-in authentication mechanisms and ensure that tokens are only accepted over secure channels with tight scope and lifetime controls.

Example of insecure token handling in Program.cs:

// Avoid: hardcoded token in code
app.Use(async (context, next) =>
{
    var token = "static-secret-token-12345";
    context.Request.Headers["Authorization"] = "Bearer " + token;
    await next();
});

This pattern embeds the token directly in application code, making it visible in source control and memory dumps. Instead, use configuration providers and environment variables.

Secure approach using configuration and policy-based authentication:

// Program.cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = builder.Configuration["Auth:Issuer"],
            ValidateAudience = true,
            ValidAudience = builder.Configuration["Auth:Audience"],
            ValidateLifetime = true,
            IssuerSigningKey = new SymmetricSecurityKey(
                Convert.FromBase64String(builder.Configuration["Auth:TokenKey"]))
        };
    });

app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/secure", () => "OK").RequireAuthorization();

Store Auth:TokenKey in environment variables or a secure vault, never in source code. Validate issuer and audience to restrict token usage to trusted sources. Ensure HTTPS is enforced so tokens are not transmitted in cleartext.

Avoid logging or reflecting the Authorization header. For example, do not write the header value to diagnostics:

// Risky: logging bearer token
var authHeader = Request.Headers["Authorization"].ToString();
_logger.LogInformation("Incoming auth: {Auth}", authHeader);

Instead, log only metadata such as endpoint name or user ID, and scrub sensitive headers. Configure the application to reject requests that contain malformed or missing bearer tokens, and use short-lived tokens with refresh mechanisms to reduce the impact of a potential leak.

For APIs consumed by third parties, define clear CORS policies and validate origins strictly:

// Program.cs
builder.Services.AddCors(options =>
{
    options.AddPolicy("ApiPolicy", policy =>
    {
        policy.WithOrigins("https://trusted-client.example.com")
              .AllowAnyHeader()
              .WithMethods("GET", "POST")
              .AllowCredentials();
    });
});
app.UseCors("ApiPolicy");

This prevents unauthorized origins from triggering requests that include bearer tokens. MiddleBrick’s checks for authentication, data exposure, and unsafe consumption validate these configurations by correlating declared security schemes with observed runtime behavior, ensuring that bearer tokens are not inadvertently exposed through permissive settings or error handling.

Frequently Asked Questions

What should I do if a bearer token is exposed in logs or error responses?
Rotate the token immediately, audit logs for further exposure, enforce HTTPS, and update configuration to avoid hardcoded values. Use short-lived tokens and monitor for anomalous requests.
How does MiddleBrick detect bearer token exposure in ASP.NET APIs?
MiddleBrick checks whether the Authorization header is transmitted over unauthenticated endpoints, appears in error messages or logs, and whether declared security schemes in OpenAPI specs match runtime behavior. It also scans outputs for token-like strings as part of its data exposure and LLM/AI security checks.