HIGH replay attackaspnetbearer tokens

Replay Attack in Aspnet with Bearer Tokens

Replay Attack in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability

A replay attack in an ASP.NET API that uses Bearer tokens occurs when an attacker intercepts a valid token and re-sends it to the server to gain unauthorized access or repeat a privileged action. Because Bearer tokens are typically static across requests (unless explicitly rotated), an intercepted token can be reused until it expires or is revoked. In ASP.NET, this risk is amplified when requests do not include mechanisms to guarantee uniqueness per transaction, such as nonce values or timestamp validation, and when transport protections are assumed sufficient without additional application-layer safeguards.

Common scenarios include APIs that accept tokens over unencrypted channels (e.g., missing HTTPS), tokens exposed in logs or browser storage, and endpoints that perform sensitive operations (e.g., money transfers, password changes) based solely on token validity without ensuring request uniqueness. Attackers can capture tokens through network sniffing, cross-site scripting (XSS), or insecure client-side storage, then replay them against endpoints recorded from legitimate traffic (e.g., using tools that replay HTTP requests).

ASP.NET’s authentication middleware validates the token signature and scope but does not inherently prevent reuse unless developers implement additional protections. Without one-time nonces, replay detection, or strict idempotency requirements, an API may treat a replayed request as legitimate if the token is valid. This aligns with common weaknesses in API security, where authentication is correctly implemented but authorization and request integrity are insufficiently enforced, a pattern often highlighted in the OWASP API Security Top 10.

For example, consider an endpoint that initiates a fund transfer. If it only checks the Bearer token and does not validate a client-supplied nonce or timestamp, an attacker can replay the same HTTP request with the same token to initiate duplicate transfers. Because the token remains valid, the server processes each request as new, illustrating how authentication alone does not prevent business-logic abuse.

Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes

To mitigate replay attacks in ASP.NET when using Bearer tokens, combine HTTPS enforcement, token short lifetimes, and application-level replay prevention such as nonce or timestamp validation. Below are concrete code examples showing how to implement these measures.

Enforce HTTPS and Secure Token Transmission

Ensure your ASP.NET application requires HTTPS and sets secure cookie/token policies. In Program.cs, enforce HTTPS redirection and configure authentication to require secure channels.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://your-auth-provider.com";
        options.Audience = "api1";
        options.RequireHttpsMetadata = true; // Enforce HTTPS for token validation
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromMinutes(1)
        };
    });

var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.Run();

Add Per-Request Nonce Validation

Include a one-time nonce in each request and store recently seen nonces (e.g., in a distributed cache) to reject duplicates. Example middleware that checks a custom X-Request-Nonce header:

app.Use(async (context, next)
{
    if (context.Request.Headers.TryGetValue("X-Request-Nonce", out var nonce))
    {
        var cache = context.RequestServices.GetRequiredService();
        var cached = await cache.GetStringAsync(nonce.ToString());
        if (cached != null)
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsync("Replay detected: nonce already used.");
            return;
        }
        await cache.SetStringAsync(nonce.ToString(), "used", new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
        });
    }
    await next();
});

Use Short-Lived Tokens and Refresh Flows

Issue access tokens with short lifetimes and use refresh tokens to obtain new access tokens. This reduces the window in which a stolen token is useful. In the client, always store tokens securely and avoid persisting them in local storage.

// Example client request with Bearer token in Authorization header
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...");
var response = await client.PostAsync("https://api.example.com/transfer", content);

Idempotency Keys for Critical Operations

For endpoints performing sensitive actions, require an idempotency key (which can be derived from or accompany the nonce) so that repeated requests with the same key are safely ignored or return the same result without side effects.

// Server-side check for idempotency key
if (context.Request.Headers.TryGetValue("Idempotency-Key", out var idempotencyKey))
{
    var idempotencyService = context.RequestServices.GetRequiredService();
    if (idempotencyService.IsDuplicate(idempotencyKey))
    {
        context.Response.StatusCode = 409;
        await context.Response.WriteAsync("Duplicate request detected.");
        return;
    }
    idempotencyService.MarkAsProcessed(idempotencyKey);
}

Frequently Asked Questions

How does middleBrick help detect replay vulnerabilities in API scans?
middleBrick runs security checks including Authentication and Unsafe Consumption in parallel, testing the unauthenticated attack surface and identifying missing replay protections such as absent nonce or idempotency requirements, with findings and remediation guidance in the report.
Can I integrate middleBrick into my CI/CD to prevent replay-related regressions?
Yes; with the Pro plan, you can use the GitHub Action to add API security checks to your CI/CD pipeline and fail builds if risk scores exceed your threshold, helping to catch replay and other issues before deployment.