Course contentsShow
← C#
Lesson 1288 of 1,90811. Identity, Security, and ClaimsFree lesson

Session Replay Defense

Implement techniques to detect and invalidate replayed authentication traffic.

In this lesson, you will learn how to defend your identity systems against attackers who intercept and re-send valid authentication tokens to impersonate your users.

The Problem: The "Replay" Vulnerability

Even when you use encrypted transport like TLS, an attacker might capture a valid authentication request or token. Because the server sees a perfectly formatted, cryptographically sound credential, it treats the request as legitimate. To stop this, we must ensure that every request is "one-time use" or strictly time-bound, effectively binding the request to a specific, unique context.

The Solution: Nonces and Timestamps

The most common technique to prevent session replay is the implementation of Nonces (Number used ONCE) and Time-to-Live (TTL) stamps. By including a unique identifier in the header of an authentication request, the server can track whether that specific request has been processed before.

Here is a simplified C# approach using a cache to track nonces:

public bool IsRequestValid(string nonce, DateTime timestamp)
{
    // 1. Check if the timestamp is too old (e.g., > 5 minutes)
    if (DateTime.UtcNow - timestamp > TimeSpan.FromMinutes(5))
        return false;

    // 2. Check the cache to see if this nonce has already been used
    if (_cache.TryGetValue(nonce, out _))
        return false; // Replay detected!

    // 3. Store the nonce in the cache until its TTL expires
    _cache.Set(nonce, true, TimeSpan.FromMinutes(5));
    return true;
}

Why This Works

By combining these two checks, you create a "window of vulnerability" that is extremely small. Even if an attacker captures the traffic, they only have a few minutes to use it before the timestamp check fails. If they attempt to use it within that window, the nonce check triggers, as the server has already "burned" that unique identifier from the first successful request.

When implementing this, ensure your nonce storage is distributed (like Redis) if your application scales horizontally; otherwise, a user might be blocked simply because their second request landed on a different server instance than the first.

Key Takeaway: To defend against session replay, enforce strict time-window validation and track unique request identifiers (nonces) to ensure each authentication token can only be successfully processed exactly once.