Logging Monitoring Failures in Aspnet with Bearer Tokens
Logging Monitoring Failures in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability
In ASP.NET APIs that rely on Bearer Token authentication, logging and monitoring failures often arise from how tokens are handled, stored, and correlated across components. When tokens are accepted but not properly validated, logged, or monitored, the API surface can expose sensitive information or allow bypassed authorization checks.
Bearer tokens are typically carried in the Authorization header as Bearer {token}. If the application does not consistently validate the token on each request, log identity context may be missing or incorrect, leading to gaps in monitoring. For example, missing or malformed tokens might be accepted silently, and the runtime identity used for logging (such as user name or scope) may be derived from an untrusted source or omitted entirely. This creates a blind spot where unauthorized access attempts can go undetected in logs and monitoring dashboards.
Another common failure is inconsistent token introspection or validation logic across endpoints. If some controllers validate the token and populate a ClaimsPrincipal while others do not, logs may show mixed identity states. Monitoring tools that rely on user or scope identifiers for aggregation will then produce incomplete or misleading views of traffic patterns, making it difficult to spot anomalies such as token reuse or privilege escalation attempts aligned with BOLA/IDOR patterns.
Additionally, logging the raw token value or including it in structured logs without redaction is a critical exposure. Tokens may appear in application telemetry, error traces, or console output, increasing the risk of accidental leakage through log aggregation systems. When monitoring dashboards correlate requests using identifiers derived from tokens, failing to mask or hash these values can inadvertently expose authentication material to anyone with access to the logs.
Runtime monitoring that does not inspect token scope and expiration can also miss signs of token misuse. For instance, requests using an expired or revoked token might still be processed if the middleware does not enforce strict validation, and such events might not be flagged in monitoring alerts. Without mapping token metadata (such as jti or custom scopes) to authorization decisions, it is harder to detect patterns like token sharing or attempts to escalate privileges across endpoints protected by Property Authorization checks.
To detect these issues, security scans such as those provided by middleBrick exercise the unauthenticated attack surface and can surface inconsistencies in how Bearer tokens are accepted, logged, and monitored. These scans do not fix the logic but highlight gaps in logging fidelity and monitoring coverage, supporting remediation that aligns with standards such as OWASP API Top 10 and common compliance frameworks.
Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes
Remediation focuses on ensuring consistent token validation, safe logging, and robust monitoring across ASP.NET pipeline components. Below are targeted code examples that illustrate secure handling of Bearer tokens.
1. Enforce authentication on all endpoints
Configure the application to require authenticated requests and ensure token validation runs for every endpoint. This prevents mixed states where some controllers validate while others do not.
// Program.cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://auth.example.com";
options.Audience = "api1";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ClockSkew = TimeSpan.FromMinutes(2)
};
});
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers().RequireAuthorization(); // ensures all endpoints require a valid token
2. Avoid logging raw tokens
Never write the token string to logs. If you must record authentication events, hash or redact the token and include only non-sensitive metadata.
// Example logger usage without exposing token
logger.LogInformation("Request processed. Subject: {Subject}, Scopes: {Scopes}, Path: {Path}",
user?.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown",
user?.FindFirst("scope")?.Value ?? "none",
context.Request.Path);
// Do NOT log: logger.LogInformation("Token: {Token}", token);
3. Include token metadata in structured logging for monitoring
Add claims such as jti (JWT ID), scope, and expiration to structured logs. This enables monitoring tools to correlate and alert on suspicious patterns without exposing the token itself.
if (user?.Identity is ClaimsIdentity identity)
{
var jti = identity.FindFirst(JwtRegisteredClaimNames.Jti)?.Value;
var scopes = identity.FindFirst("scope")?.Value;
logger.LogInformation("ApiAccess TokenClaims",
new EventId(),
new Dictionary<string, object>
{
{ "jti", jti ?? Guid.NewGuid() },
{ "scopes", scopes ?? "none" },
{ "timestamp", DateTimeOffset.UtcNow.ToUnixTimeSeconds() }
});
}
4. Consistent policy-based authorization with resource scoping
Use policies that reference resource-based identifiers to mitigate BOLA/IDOR and Property Authorization issues. Validate ownership or tenant context after token validation, and log authorization decisions with token metadata for traceability.
services.AddAuthorizationBuilder()
.AddPolicy("DocumentAccess", policy =>
policy.RequireAssertion(context =>
{
var user = context.User;
var docId = context.Resource?.GetType().GetProperty("OwnerId")?.GetValue(context.Resource)?.ToString();
var userId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
bool hasAccess = docId == userId;
if (!hasAccess)
{
logger.LogWarning("Authorization denied. UserId: {UserId}, ResourceId: {ResourceId}", userId, docId);
}
return hasAccess;
}));
// Usage in controller
[HttpGet("{id}")]
[Authorize(Policy = "DocumentAccess")]
public IActionResult GetDocument(Guid id) { /* ... */ }
5. Monitor token anomalies via middleware
Add lightweight middleware to capture and monitor abnormal token usage, such as repeated use of the same jti or tokens presented without proper scope. This data feeds into monitoring dashboards to trigger alerts.
app.Use(async (context, next) =>
{
var token = context.Request.Headers["Authorization"].ToString()?.Replace("Bearer ", "");
if (!string.IsNullOrEmpty(token))
{
// Example: extract jti from validated principal if available
var jti = context.User?.FindFirst(JwtRegisteredClaimNames.Jti)?.Value;
// Send metrics to monitoring system (pseudocode)
// metrics.TrackTokenUse(jti, context.Request.Path, context.Response.StatusCode);
}
await next();
});
By standardizing validation, redacting sensitive values in logs, and enriching structured telemetry with token metadata, teams can close logging and monitoring gaps specific to Bearer token flows. These changes complement scans from tools like middleBrick, which highlight misconfigurations and support remediation aligned with compliance requirements.