Skip to main content

Lesson 5 of 8

Refresh Token Family Invalidation

If a malicious actor steals a refresh token and uses it, your system must detect and respond: if the stolen token is used AFTER the legitimate user already rotated it, the old token is no longer valid - and you can detect this. Refresh token families allow detecting such replay attacks.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Token Family & Replay Detection

Token Family & Replay Detection
// ━━ RefreshToken entity with family tracking ━━
public class RefreshToken
{
    public Guid Id { get; set; }
    public string TokenHash { get; set; } = "";     // BCrypt hash of the raw token
    public string UserId { get; set; } = "";
    public string FamilyId { get; set; } = "";       // all tokens in a sign-in chain share this
    public bool IsRevoked { get; set; }
    public DateTime ExpiresAt { get; set; }
    public DateTime CreatedAt { get; set; }
    public Guid? ReplacedByTokenId { get; set; }    // which new token replaced this one
}

// ━━ Rotation with replay detection ━━
public class AuthService(
    IRefreshTokenRepository tokenRepo,
    UserManager<ApplicationUser> userManager,
    TokenService tokenService)
{
    public async Task<Result<AuthResponse>> RefreshAsync(
        string rawRefreshToken, CancellationToken ct)
    {
        // Find token by scanning active tokens for this hash
        var allActive = await tokenRepo.GetActiveByFamilyHashAsync(rawRefreshToken, ct);

        if (allActive is null)
        {
            // Token not found - may be completely forged
            return Result<AuthResponse>.Unauthorized("Invalid refresh token");
        }

        if (allActive.IsRevoked)
        {
            // REPLAY ATTACK DETECTED: token was already used!
            // Revoke entire family - force all devices to re-login
            await tokenRepo.RevokeEntireFamilyAsync(allActive.FamilyId, ct);
            return Result<AuthResponse>.Unauthorized(
                "Security alert: token reuse detected. All sessions revoked.");
        }

        if (allActive.ExpiresAt < DateTime.UtcNow)
            return Result<AuthResponse>.Unauthorized("Refresh token expired");

        var user = await userManager.FindByIdAsync(allActive.UserId);
        if (user is null || !user.IsActive)
            return Result<AuthResponse>.Unauthorized("User account disabled");

        // Mark old token as revoked (but keep it for audit)
        allActive.IsRevoked = true;
        await tokenRepo.UpdateAsync(allActive, ct);

        // Issue new token in same family
        var newRaw = TokenService.GenerateRefreshToken();
        var newToken = new RefreshToken
        {
            Id = Guid.NewGuid(),
            TokenHash = BCrypt.Net.BCrypt.HashPassword(newRaw),
            UserId = user.Id,
            FamilyId = allActive.FamilyId, // same family
            ExpiresAt = DateTime.UtcNow.AddDays(7),
            CreatedAt = DateTime.UtcNow
        };
        allActive.ReplacedByTokenId = newToken.Id;
        await tokenRepo.CreateAsync(newToken, ct);

        var roles = await userManager.GetRolesAsync(user);
        var accessToken = tokenService.GenerateAccessToken(user, roles);

        return Result<AuthResponse>.Success(new AuthResponse(accessToken, newRaw));
    }
}

record AuthResponse(string AccessToken, string RefreshToken);
record Result<T>(bool IsSuccess, T? Value = default, string? Error = null)
{
    public static Result<T> Success(T v) => new(true, v);
    public static Result<T> Unauthorized(string e) => new(false, Error: e);
}
interface IRefreshTokenRepository
{
    Task<RefreshToken?> GetActiveByFamilyHashAsync(string rawToken, CancellationToken ct);
    Task RevokeEntireFamilyAsync(string familyId, CancellationToken ct);
    Task UpdateAsync(RefreshToken t, CancellationToken ct);
    Task CreateAsync(RefreshToken t, CancellationToken ct);
}
class ApplicationUser { public string Id { get; set; } = ""; public string? Email { get; set; } public bool IsActive { get; set; } }

Tip

Tip

Practice Refresh Token Family Invalidation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Refresh Token Family Invalidation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Refresh Token Family Invalidation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done