Token Leakage in Aspnet with Bearer Tokens
Token Leakage in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability
Token leakage in ASP.NET applications using Bearer tokens occurs when access tokens are exposed beyond the intended trust boundary, enabling unauthorized access to protected resources. Bearer tokens are security credentials that grant access to the holder; if they leak, any possessor can impersonate the associated identity. Several vectors are common in ASP.NET environments: insecure logging that writes Authorization headers to application or server logs, client-side storage in browser local storage or session storage that is readable via XSS, and accidental inclusion of tokens in URLs or query strings that can be captured in server logs, Referer headers, or browser history.
In ASP.NET Core, developers often configure authentication via AddAuthentication and AddJwtBearer. If the application does not enforce HTTPS strictly or if development configurations accidentally allow HTTP, tokens can be intercepted in transit. A typical insecure setup might look like this, where the token is expected to arrive via the Authorization header but the application lacks mandatory HTTPS redirection and does not validate token audiences properly:
// Insecure Startup/Program configuration example (do not use)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer(options =>
{
options.Authority = "https://insecure-identity.example.com";
options.Audience = "api.example.com";
// Missing RequireHttpsMetadata = true in non-production
// Missing TokenValidationParameters validations
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/items", (HttpRequest req) =>
{
// Token may be logged inadvertently
var authHeader = req.Headers["Authorization"];
Logger.LogInformation("Authorization header: {Auth}", authHeader);
return Results.Ok(new { data = "sensitive" });
});
app.Run();
Additionally, token leakage can arise from improper handling of cross-origin requests and CORS. If CORS is misconfigured to allow credentials without strict origin policies, tokens may be exposed to origins that should not have access. Another leakage path is error messages that inadvertently include Authorization header values in responses or stack traces, which can be harvested by attackers probing the API. MiddleBrick’s scans include checks for these patterns, flagging issues such as missing HTTPS enforcement, overly permissive CORS, and endpoints that reflect Authorization headers in responses or logs.
Because Bearer tokens are often stored in browser storage to persist sessions, they become susceptible to XSS. If an attacker can inject script into the application, they can read tokens from localStorage or sessionStorage and exfiltrate them. In single-page applications consuming ASP.NET APIs, failing to set the Secure and SameSite attributes on cookies used for token delivery, or failing to implement anti-CSRF measures when tokens are stored in cookies, increases the risk. Even when tokens are stored in memory, if the application does not short-lived token lifetimes and does not implement proper token revocation, leaked tokens remain useful for extended windows.
ASP.NET applications that integrate with identity providers such as Azure AD or IdentityServer must ensure that token validation is strict: validate issuer, audience, lifetime, and signing keys. Without these validations, an attacker might supply a stolen token that the server accepts if the configuration is lax. MiddleBrick’s LLM/AI Security and Input Validation checks can highlight endpoints that process Authorization headers unsafely and may expose tokens through verbose error messages or misconfigured Swagger/OpenAPI specs that inadvertently document token handling in examples.
Finally, the combination of OpenAPI/Swagger spec analysis with runtime findings is valuable: specs may define securitySchemes as type: http with scheme: bearer, but runtime behavior might not enforce HTTPS or may leak tokens in redirects or logs. By correlating spec definitions with actual responses, scanners can identify mismatches where the implementation does not match the declared security expectations, helping teams close gaps that lead to token leakage.
Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes
To remediate token leakage in ASP.NET, enforce HTTPS, validate tokens strictly, avoid logging sensitive headers, and store tokens securely. Below are concrete code examples showing secure configurations and practices that reduce the risk of Bearer token exposure.
1. Enforce HTTPS and secure token validation
Ensure RequireHttpsMetadata is enabled in production and token validation is strict. This prevents tokens from being transmitted in cleartext and ensures only tokens issued by a trusted authority are accepted:
// Secure Program/Startup configuration
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://secure-identity.example.com";
options.Audience = "api.example.com";
options.RequireHttpsMetadata = true; // enforce HTTPS
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "https://secure-identity.example.com",
ValidAudience = "api.example.com",
ClockSkew = TimeSpan.FromMinutes(2)
};
});
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
2. Avoid logging Authorization headers
Never log raw Authorization headers. If you must log for diagnostics, sanitize or hash the token. Here is a safe approach that redacts the token value:
app.MapGet("/secure-endpoint", (HttpRequest req) =>
{
var authHeader = req.Headers["Authorization"].ToString();
// Safe: do not log the raw token
Logger.LogInformation("Authorization header present: {HasAuth}, sanitized", !string.IsNullOrEmpty(authHeader));
// Process token via authentication middleware; do not echo it
return Results.Ok(new { message = "secure" });
});
3. Use secure storage for tokens on the client and configure cookies safely
If your ASP.NET app issues tokens via cookies (for example in a SPA backend), set Secure, HttpOnly, and SameSite attributes. For Bearer usage in JavaScript clients, store tokens in memory or in secure, httpOnly cookies rather than localStorage when possible:
app.UseSession(options =>
{
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Strict;
});
// Example of issuing a cookie with a token (if using cookie-based flows)
app.MapPost("/login", (HttpContext context) =>
{
var token = GenerateSecureToken();
context.Response.Cookies.Append("auth_token", token, new CookieOptions
{
Secure = true,
HttpOnly = true,
SameSite = SameSiteMode.Strict,
Expires = DateTimeOffset.UtcNow.AddMinutes(30)
});
return Results.Ok();
});
4. Implement short lifetimes and refresh token rotation
Reduce the impact of leaked tokens by issuing short-lived access tokens and using refresh tokens with rotation. Below is an example of configuring token lifetimes in AddJwtBearer and validating them:
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateLifetime = true,
// Accept tokens within a short window
ClockSkew = TimeSpan.FromMinutes(2)
};
// Ensure your token issuer sets exp (expiration) to a short duration,
// e.g., 15 minutes, and issues refresh tokens with rotation.
5. Harden CORS and prevent token leakage via Referer or client-side storage
Configure CORS to avoid sending credentials to untrusted origins and prevent tokens from being leaked via the Referer header:
builder.Services.AddCors(options =>
{
options.AddPolicy("SecurePolicy", policy =>
{
policy.WithOrigins("https://trusted.example.com")
.AllowAnyHeader()
.AllowAnyMethod()
.WithExposedHeaders("X-Custom-Header")
.AllowCredentials(); // only if necessary and origins are strict
});
});
app.UseCors("SecurePolicy");
Additionally, serve your SPA with Content Security Policy (CSP) headers to mitigate XSS, which is a common vector for stealing tokens stored in client-side storage.
6. Scan and validate OpenAPI specs for unsafe examples
Ensure that your OpenAPI spec does not include example values for Authorization headers that could be mistakenly used in production. Use MiddleBrick’s spec analysis to detect mismatches between declared security schemes and runtime behavior, and remove any example tokens from documentation.
// openapi.yaml excerpt — avoid storing real tokens in examples
paths:
/items:
get:
summary: Get items
security:
- bearerAuth: []
responses:
'200':
description: OK
# Do not include real token examples in spec
By combining strict HTTPS enforcement, precise token validation, secure cookie settings, short lifetimes, robust CORS, and careful handling of logs and documentation, you significantly reduce token leakage risks in ASP.NET applications.