Denial Of Service in Aspnet with Bearer Tokens
Denial Of Service in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability
In ASP.NET APIs that use Bearer token validation, certain patterns can amplify Denial of Service (DoS) risks. Bearer tokens are typically validated on each request, and if validation logic is inefficient or misconfigured, it can become a bottleneck or an abuse vector. For example, when token validation involves expensive cryptographic operations or repeated database lookups without caching, high request rates can consume thread pool and CPU resources, leading to service unavailability.
Consider an endpoint that validates a JWT Bearer token on every call and, in addition, performs a synchronous database query to check token revocation status. An attacker can flood the endpoint with requests carrying valid-format but invalid or revoked tokens, forcing the server to perform costly checks for each request. This can exhaust thread pool threads, cause request queueing, and increase latency for legitimate users. In some cases, missing or weak rate limiting allows this behavior to escalate into a resource-exhaustion DoS scenario.
ASP.NET’s built-in Bearer token handling (e.g., using AddAuthentication and AddJwtBearer) is generally efficient, but application-level customizations can reintroduce risk. For instance, attaching large claims transformations or custom authorization logic that iterates over token payloads on every request may increase per-request processing time. If these handlers are not asynchronous or are blocking, they can degrade throughput under load. The combination of Bearer token validation and high concurrency can also expose race conditions or lock contention in custom token caches, further contributing to instability.
Because middleBrick scans the unauthenticated attack surface, it can detect endpoints that accept Bearer tokens and exhibit signs of inefficient validation or missing rate controls. Findings may highlight missing rate limiting on token-validation paths, absence of anti-automation protections, or observable delays when invalid tokens are submitted. These observations do not imply that middleBrick tests authenticated state, but they surface the unauthenticated attack surface where token-based endpoints are reachable and potentially strain server resources when abused.
Leveraging tools such as the middleBrick Web Dashboard and CLI, teams can track security scores over time and integrate scanning into CI/CD pipelines. The middleBrick GitHub Action can add API security checks to your CI/CD pipeline and fail builds if risk scores drop below a chosen threshold. For rapid local iteration, the CLI allows you to scan from the terminal using middlebrick scan
Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes
Remediation focuses on efficient token validation, caching, and request management to reduce the DoS surface when Bearer tokens are used. Apply the following patterns in ASP.NET Core to keep per-request work minimal and resilient under load.
First, ensure token validation is asynchronous and avoids blocking calls. Use AddJwtBearer with events to customize behavior without introducing synchronous work. The following example configures Bearer token validation with a short clock-skew tolerance and a remote validation that avoids expensive synchronous checks.
// Program.cs or Startup.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "https://auth.example.com/",
ValidateAudience = true,
ValidAudience = "api://resource-server",
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(2),
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("very-long-key-placeholder-change-in-production"))
};
// Keep token processing asynchronous where possible
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
context.Token = context.Request.Cookies["access_token"];
return Task.CompletedTask;
}
};
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/secure", () => "Authenticated");
app.Run();
Second, offload revocation and policy checks to a cache with TTL to avoid per-request database queries. If you must validate revocation, use an asynchronous, cached lookup with a short TTL to reduce backend load. Below is an example using IDistributedCache to remember revocation status briefly.
// TokenCacheService.cs
using System.Runtime.Caching;
public class TokenCacheService
{
private readonly ObjectCache _cache = MemoryCache.Default;
public void AddRevoked(string jti, TimeSpan expiry)
{
_cache.Set(jti, "revoked", DateTimeOffset.UtcNow.Add(expiry));
}
public bool IsRevoked(string jti)
{
return _cache.Get(jti) != null;
}
}
// In JwtBearer.Events or a custom handler
app.Use(async (context, next) =>
{
var token = context.Request.Headers["Authorization"].ToString()?.Replace("Bearer ", "");
if (!string.IsNullOrEmpty(token))
{
var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
if (handler.CanReadToken(token))
{
var jwt = handler.ReadJwtToken(token);
var jti = jwt.Id;
var cacheService = context.RequestServices.GetRequiredService<TokenCacheService>();
if (cacheService.IsRevoked(jti))
{
context.Response.StatusCode = 401;
return;
}
}
}
await next();
});
Third, apply rate limiting at the endpoint or global level to prevent flooding of token-validation paths. Use ASP.NET Core rate limiting policies to cap requests per client or per token scope. The following policy limits anonymous and authenticated bursts to reduce strain on token validation logic.
// Program.cs
builder.Services.AddRateLimiter(options =>
{
options.GlobalLimiter = PartitionedRateLimiter.Create(context =>
{
var identity = context.User.Identity?.Name ?? context.Request.Headers["Authorization"].ToString();
return RateLimitPartition.GetFixedWindowLimiter(
partitionKey: identity ?? "anonymous",
factory: _ => new FixedWindowRateLimiterOptions
{
AutoReplenishment = true,
PermitLimit = 100,
Window = TimeSpan.FromSeconds(10)
});
});
});
app.UseRateLimiter();
Finally, avoid synchronous or long-running work inside token validation events. Keep event handlers lightweight and return quickly. If you need to perform expensive checks, consider background processing or short-term caches. The middleBrick CLI can be used in scripts to verify that token-accepting endpoints remain responsive under simulated load, and the middlebrick scan
Related CWEs: resourceConsumption
| CWE ID | Name | Severity |
|---|---|---|
| CWE-400 | Uncontrolled Resource Consumption | HIGH |
| CWE-770 | Allocation of Resources Without Limits | MEDIUM |
| CWE-799 | Improper Control of Interaction Frequency | MEDIUM |
| CWE-835 | Infinite Loop | HIGH |
| CWE-1050 | Excessive Platform Resource Consumption | MEDIUM |