HIGH information disclosureaspnetbearer tokens

Information Disclosure in Aspnet with Bearer Tokens

Information Disclosure in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Information disclosure in ASP.NET applications using Bearer tokens occurs when sensitive authentication material or related data is exposed through endpoints, logs, error messages, or misconfigured authorization. When Bearer tokens are handled without adequate safeguards, an unauthenticated or low-privilege attacker may learn token values, session identifiers, or implementation details that enable further compromise.

One common pattern involves ASP.NET endpoints that return JSON responses containing token metadata, debug details, or stack traces that include token fragments. For example, an endpoint that echoes a token for introspection or validation might accidentally include the raw token in logs or responses when exceptions occur. Consider an API that decodes a JWT to inspect claims but fails to sanitize output:

// Example: unsafe token inspection in ASP.NET Core
var handler = new JwtSecurityTokenHandler();
var token = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
if (handler.CanReadToken(token))
{
    var jwt = handler.ReadJwtToken(token);
    // Risk: returning raw token or claims in response can leak sensitive data
    return Ok(new { Token = token, Claims = jwt.Claims });
}

In this pattern, returning the raw token in the response body can lead to inadvertent leakage if the response is logged or cached. Additionally, ASP.NET applications that include detailed error messages in development or misconfigured CORS can expose token-related information. An attacker who triggers an error on an endpoint that processes Bearer tokens may receive stack traces that reveal how tokens are validated, stored, or transformed, aiding further attacks such as token replay or privilege escalation.

Another vector involves insecure handling of tokens in middleware or during serialization. If an ASP.NET application serializes tokens into logs, HTTP response headers, or query strings without encryption or truncation, scanners can detect these exposures. For instance, writing tokens into diagnostic logs without masking means that anyone with log access can harvest valid credentials. Similarly, if an endpoint accepts a Bearer token in the URL query string instead of the Authorization header, tokens may be stored in browser history or proxy logs, increasing exposure risk.

ASP.NET’s default behavior around authentication schemes and cookie policies can also contribute to information leakage when Bearer tokens are used in hybrid flows. Misconfigured authentication middleware might emit verbose messages when token validation fails, revealing whether a token was malformed, expired, or missing. These messages can be enumerated by an attacker to infer valid versus invalid tokens, effectively performing unauthorized authentication checks.

To reliably detect these issues, middleBrick runs checks that map findings to frameworks such as OWASP API Top 10 and PCI-DSS. The scanner compares runtime behavior against OpenAPI/Swagger specifications (2.0, 3.0, 3.1) with full $ref resolution, cross-referencing spec definitions with observed responses. For example, if an endpoint documentation claims it does not return tokens but runtime inspection shows token-like values in responses or logs, this is flagged as a data exposure finding with severity and remediation guidance.

Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes

Remediation focuses on ensuring Bearer tokens are never exposed in responses, logs, or error messages, and are handled strictly according to security best practices. Below are concrete code examples for ASP.NET Core that demonstrate secure handling.

1. Do not return tokens in responses

Ensure endpoints that validate or introspect tokens do not echo the raw token back to the client. Instead, return only necessary claims or status.

// Secure token introspection in ASP.NET Core
var handler = new JwtSecurityTokenHandler();
var authHeader = Request.Headers["Authorization"].ToString();
if (authHeader.StartsWith("Bearer "))
{
    var token = authHeader.Substring("Bearer ".Length);
    if (handler.CanReadToken(token))
    {
        var jwt = handler.ReadJwtToken(token);
        // Return only required claims, not the token itself
        var claims = jwt.Claims.Select(c => new { c.Type, c.Value });
        return Ok(new { Claims = claims });
    }
    return Unauthorized();
}

2. Use secure authentication and avoid query strings

Always prefer the Authorization header for Bearer tokens. Do not accept tokens via query parameters.

// Configure authentication to require header-based Bearer tokens
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = Configuration["Auth:Issuer"],
            ValidAudience = Configuration["Auth:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(Configuration["Auth:Key"]))
        };
    });

3. Suppress token details in exceptions and logs

Ensure exceptions do not include raw tokens and logs mask token values.

// Example of exception handling that avoids leaking tokens
try
{
    // token validation logic
}
catch (SecurityTokenException ex)
{
    // Log without the token
    _logger.LogWarning(ex, "Token validation failed");
    return Unauthorized();
}

In production, configure logging providers to scrub sensitive fields. For diagnostic logs, apply masking:

// Mask token in logs (example using structured logging)
var token = authHeader.StartsWith("Bearer ") ? authHeader.Substring("Bearer ".Length) : "[masked]";
_logger.LogInformation("Processing request with token: {Token}", token);

4. Enforce HTTPS and secure cookie policies for hybrid flows

If your application mixes authentication schemes, enforce HTTPS and avoid persisting tokens in insecure storage.

// Enforce HTTPS and secure policies in ASP.NET Core
app.UseHttpsRedirection();
services.ConfigureApplicationCookie(options =>
{
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.Cookie.HttpOnly = true;
    options.Cookie.SameSite = SameSiteMode.Strict;
});

5. Validate and limit token scope

Always validate token scope and claims to ensure least privilege, and avoid accepting unsigned or weakly signed tokens.

// Validate token audience and issuer strictly
var validationParams = new TokenValidationParameters
{
    ValidAudience = Configuration["Auth:Audience"],
    ValidIssuer = Configuration["Auth:Issuer"],
    ClockSkew = TimeSpan.Zero
};
// Use policy-based authorization to enforce scope requirements
services.AddAuthorization(options =>
{
    options.AddPolicy("RequireScope", policy =>
        policy.RequireClaim("scope", "api.read"));
});

By applying these patterns, ASP.NET applications reduce the likelihood of information disclosure when Bearer tokens are used. middleBrick’s scans can verify that such remediations are reflected in runtime behavior and that no endpoints inadvertently expose tokens or related metadata.

Frequently Asked Questions

Can an endpoint that returns Bearer tokens in error messages lead to information disclosure?
Yes. If error messages or stack traces include raw tokens or token metadata, attackers can harvest credentials or infer validation logic, leading to information disclosure. Ensure errors are generic and tokens are never echoed.
How does middleBrick detect information disclosure involving Bearer tokens in ASP.NET APIs?
middleBrick compares OpenAPI/Swagger specs (with full $ref resolution) against runtime responses and logs for token-like values. Findings are mapped to frameworks such as OWASP API Top 10 and include severity and remediation guidance.