C# / .NET Compendium PLEN
.NET / C# / Security

Refresh token: how it works and when to use it

The problem it solves

An access token (usually a JWT) is self-contained: the API checks its signature and asks nobody for an opinion, so it can't easily be revoked. That is why it should live briefly (5-15 minutes). A short token limits the damage after theft, but the user doesn't want to log in every few minutes. The solution is a second token: the refresh token. The wider context (JWT, OAuth 2.0, OIDC) is in the topic Securing a Web API.

What a refresh token is

  • A long-lived (days or weeks) secret whose only job is to obtain a new access token without entering the password again.
  • Usually opaque: a random string, not a JWT. There is nothing inside it, and the server knows its meaning from the database.
  • Sent only to the token endpoint (the authorization server), never to the API with resources. Thanks to this it is rarely exposed to interception.
  • In OAuth 2.0 it is obtained through the offline_access scope (in OIDC) and exchanged through grant_type=refresh_token.
Access token Refresh token
What for access to the API getting a new access token
Lifetime short (minutes) long (days, weeks)
Where it is sent to every API with resources only to the token server
Format usually a JWT (self-contained) usually random, opaque
Revocation hard (waits until it expires) easy (the server holds its state)
Theft risk limited by time greater, so it requires protection and rotation

The flow step by step

1. Client --- login + password ----------------------------> Token server
   Klient <-- access token (60 s) + refresh token (7 dni) --

2. Klient --- access token -----------------------------> API  --> 200 OK

3. (after 60 s) Client --- access token ------------------> API  --> 401 (expired)

4. Client --- refresh token ----------------------------> Token server
   Client <-- NEW access token + NEW refresh token ----   (the old refresh token stops working)

5. Klient --- nowy access token ------------------------> API  --> 200 OK

An OAuth 2.0 refresh request looks like this:

POST /token
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token&refresh_token=<token>&client_id=my-spa

Rotation and reuse detection (the most important security mechanism)

A refresh token's long life is itself a risk: whoever steals it can generate new access tokens forever. That is why rotation is used:

  1. Every refresh token is single-use. After use the server issues a new one and invalidates the old one.
  2. The tokens of one login form a family, i.e. a chain of successive rotations.
  3. If a refresh token that has already been used comes back to the server (reuse detection), it means someone copied it: the legitimate user and the thief have the same token. The server invalidates the whole family, which forces a new login and kicks out the thief.

This is a recommendation from the OAuth 2.0 Security Best Current Practice for public clients (SPAs, mobile apps).

Where and how to store it

On the client side:

  • SPA: best in a HttpOnly; Secure; SameSite cookie set by your own backend (the BFF pattern), so that JavaScript has no access to it. localStorage is vulnerable to theft through XSS.
  • A mobile app: in the system's secure store (iOS Keychain, Android Keystore).
  • A server or desktop application: an encrypted store (DPAPI, Key Vault).

On the server side:

  • Store only the hash of the token (SHA-256 is enough, because the token is random and long, unlike passwords, which need a slow salted hash), not the token itself.
  • Store: the user identifier, the family, the expiry date, the "used" and "revoked" flags, and where needed the device or IP address.
  • A unique index on the hash and the rotation operation in one transaction, so that two parallel requests can't use the same token.
  • The expiry date: absolute (e.g. 30 days from login) or sliding, often both at once.
  • Logging out is revoking the family. You can also allow "log out of all devices".

When to use it

  • Yes: SPAs and mobile apps, where the user is meant to stay logged in for days (a short access token, a long session).
  • Yes: when you need the ability to revoke a user's access without waiting for the JWT to expire.
  • Not needed: service-to-service communication (OAuth 2.0 Client Credentials) - the client simply fetches a new access token using its secret or certificate.
  • Not needed: short sessions after which logging in again doesn't matter, and cookie sessions in classic MVC.
  • Don't try to write this yourself if you have an identity provider: Entra ID, Keycloak, Auth0 and Duende IdentityServer have rotation and reuse detection. In ASP.NET Core 8 MapIdentityApi also exposes a /refresh endpoint.

A working example - RefreshTokenDemo

A minimal API (.NET 8, the Microsoft.AspNetCore.Authentication.JwtBearer package): login issues an access token valid for 60 seconds and a refresh token, /refresh does the rotation, and reusing an old token invalidates the whole family.

using System.Security.Cryptography;
using System.Text;

public enum RotateStatus { Ok, Invalid, ReuseDetected }

public class RefreshTokenRecord
{
    public string Hash { get; init; } = string.Empty;      // only the HASH is stored, never the token itself
    public string UserId { get; init; } = string.Empty;
    public string FamilyId { get; init; } = string.Empty;  // all tokens of one login (one chain of rotations)
    public DateTime ExpiresAt { get; init; }
    public bool Used { get; set; }
    public bool Revoked { get; set; }
}

// In-memory store for the demo. In production: a database table with a unique index on Hash,
// and Rotate() as one transaction (so two parallel requests cannot both use the same token).
public class RefreshTokenStore
{
    private static readonly TimeSpan Lifetime = TimeSpan.FromDays(7); // absolute lifetime of one token
    private readonly Dictionary<string, RefreshTokenRecord> _tokens = new();
    private readonly object _lock = new();

    public string Create(string userId, string familyId)
    {
        // opaque, random, high-entropy value (NOT a JWT)
        var raw = Convert.ToBase64String(RandomNumberGenerator.GetBytes(64))
            .Replace('+', '-').Replace('/', '_').TrimEnd('=');

        var record = new RefreshTokenRecord
        {
            Hash = Hash(raw),
            UserId = userId,
            FamilyId = familyId,
            ExpiresAt = DateTime.UtcNow.Add(Lifetime)
        };

        lock (_lock) _tokens[record.Hash] = record;
        return raw;
    }

    // Rotation: a refresh token can be used ONCE; the answer contains a brand new refresh token.
    public (RotateStatus Status, string? UserId, string? NewToken) Rotate(string raw)
    {
        lock (_lock)
        {
            if (!_tokens.TryGetValue(Hash(raw), out var record)
                || record.Revoked
                || record.ExpiresAt < DateTime.UtcNow)
                return (RotateStatus.Invalid, null, null);

            if (record.Used)
            {
                // An already used token came back: either the client is buggy or the token was STOLEN
                // (the thief and the owner both hold it). Safest reaction: kill the whole family.
                RevokeFamily(record.FamilyId);
                return (RotateStatus.ReuseDetected, null, null);
            }

            record.Used = true;
            var next = Create(record.UserId, record.FamilyId); // same family, new token
            return (RotateStatus.Ok, record.UserId, next);
        }
    }

    // Logout: revoke the whole chain, so no refresh token of this login works any more.
    public void Revoke(string raw)
    {
        lock (_lock)
        {
            if (_tokens.TryGetValue(Hash(raw), out var record)) RevokeFamily(record.FamilyId);
        }
    }

    private void RevokeFamily(string familyId)
    {
        foreach (var t in _tokens.Values.Where(t => t.FamilyId == familyId)) t.Revoked = true;
    }

    // SHA-256 is enough here: the token is random and long, so it cannot be guessed or brute-forced
    // (unlike passwords, which need a slow hash with a salt).
    private static string Hash(string raw) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(raw)));
}
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

// DEMO ONLY: in production tokens come from an identity provider and the key is not stored in code.
const string Issuer = "https://demo.local";
const string Audience = "demo-api";
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("demo-key-change-me-at-least-32-bytes-long!!"));
var accessLifetime = TimeSpan.FromSeconds(60); // SHORT on purpose, so you can watch it expire

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.MapInboundClaims = false;
        o.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true, ValidIssuer = Issuer,
            ValidateAudience = true, ValidAudience = Audience,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero, // no tolerance, so expiry is visible exactly after 60 s
            ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey,
            ValidAlgorithms = new[] { SecurityAlgorithms.HmacSha256 }
        };
    });
builder.Services.AddAuthorization();
builder.Services.AddSingleton<RefreshTokenStore>();

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

string CreateAccessToken(string userId)
{
    var token = new JwtSecurityToken(Issuer, Audience,
        claims: new[] { new Claim("sub", userId) },
        expires: DateTime.UtcNow.Add(accessLifetime),
        signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256));
    return new JwtSecurityTokenHandler().WriteToken(token);
}

var users = new Dictionary<string, string> { ["alice"] = "alice123", ["bob"] = "bob123" };

// 1) Login: the user proves who they are ONCE and gets a pair of tokens.
app.MapPost("/login", (LoginRequest request, RefreshTokenStore store) =>
{
    if (!users.TryGetValue(request.Username, out var password) || password != request.Password)
        return Results.Unauthorized();

    var refresh = store.Create(request.Username, familyId: Guid.NewGuid().ToString("N"));
    return Results.Ok(new TokenResponse(CreateAccessToken(request.Username), (int)accessLifetime.TotalSeconds, refresh));
});

// 2) Refresh: exchange a refresh token for a NEW pair (no password needed, the old refresh token dies).
app.MapPost("/refresh", (RefreshRequest request, RefreshTokenStore store) =>
{
    var (status, userId, newRefresh) = store.Rotate(request.RefreshToken);
    return status switch
    {
        RotateStatus.Ok => Results.Ok(new TokenResponse(CreateAccessToken(userId!), (int)accessLifetime.TotalSeconds, newRefresh!)),
        RotateStatus.ReuseDetected => Results.Json(
            new { error = "refresh token reuse detected - the whole session was revoked, log in again" },
            statusCode: StatusCodes.Status401Unauthorized),
        _ => Results.Unauthorized()
    };
});

// 3) Logout: the refresh token chain is revoked (the access token still lives until it expires).
app.MapPost("/logout", (RefreshRequest request, RefreshTokenStore store) =>
{
    store.Revoke(request.RefreshToken);
    return Results.NoContent();
});

// A protected resource: only the ACCESS token is sent here, never the refresh token.
app.MapGet("/api/me", (ClaimsPrincipal user) => new
{
    user = user.FindFirstValue("sub"),
    accessTokenExpiresAtUtc = DateTimeOffset.FromUnixTimeSeconds(long.Parse(user.FindFirstValue("exp")!))
}).RequireAuthorization();

app.Run();

record LoginRequest(string Username, string Password);
record RefreshRequest(string RefreshToken);
record TokenResponse(string AccessToken, int ExpiresIn, string RefreshToken);

The project (RefreshTokenDemo.csproj):

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
  </ItemGroup>

</Project>

How to try it

dotnet run (address http://localhost:5002), then a requests.http file or curl:

# 1) log in: access token (60 s) + refresh token
curl -X POST http://localhost:5002/login -H "Content-Type: application/json" \
     -d '{"username":"alice","password":"alice123"}'

# 2) call the API with the access token -> 200 (after 60 s -> 401)
curl http://localhost:5002/api/me -H "Authorization: Bearer <accessToken>"

# 3) refresh: new pair of tokens, the old refresh token dies
curl -X POST http://localhost:5002/refresh -H "Content-Type: application/json" \
     -d '{"refreshToken":"<refreshToken>"}'

# 4) reuse the OLD refresh token -> 401 "reuse detected", and now even the newest one is dead
curl -i -X POST http://localhost:5002/refresh -H "Content-Type: application/json" \
     -d '{"refreshToken":"<old refreshToken>"}'

What this example shows

  • A short access token (ClockSkew = Zero, 60 s), so the expiry is visible to the naked eye.
  • The refresh token is a random string, and only its SHA-256 hash is in the store.
  • Rotation: after /refresh the old token is marked as used, and the response contains a new one.
  • Reuse detection: reusing an old token invalidates the whole family (RevokeFamily).
  • Atomicity: Rotate runs under a lock. In a database it must be a single transaction with a unique index.
  • Logging out invalidates the chain of tokens, but the access token lives until it expires (which is why it should be short).

A database variant (EF Core) - RefreshTokenDbDemo

In production the refresh token store is a table in a database, not a Dictionary. The full project (SQLite, port 5003, the same scenario in requests.http) is in examples/RefreshTokenDbDemo. Below are the most important fragments.

What changes compared with the in-memory version:

  • When generating a token you don't check whether it already exists. The token has 512 bits of entropy, so a collision is practically impossible. A manual "check and insert" would be a race anyway, so instead: a unique index on TokenHash and drawing again if the database rejects the write.
  • On refresh you look the token up by its hash. There is no entry, or it is expired or revoked: 401. It has already been used: revoke the family and 401. It is valid: mark it as used and issue a new one.
  • Marking as used has to be atomic. A plain "read, check the flag, save" has the same race as a Dictionary without lock. The solution: a single conditional UPDATE (ExecuteUpdateAsync) that changes UsedAt only if the token is still unused, and returns the number of rows changed. Exactly one of the parallel requests gets 1, the rest 0. It also works with many instances of the application, which an in-memory lock can't ensure.
  • The raw token never goes into the database or the logs, only its hash.
using Microsoft.EntityFrameworkCore;

public class RefreshToken
{
    public Guid Id { get; set; }
    public string TokenHash { get; set; } = string.Empty;  // only the HASH is stored (unique index)
    public string UserId { get; set; } = string.Empty;
    public Guid FamilyId { get; set; }                     // all tokens of one login (index)
    public DateTime ExpiresAt { get; set; }
    public DateTime? UsedAt { get; set; }                  // set exactly once, atomically
    public DateTime? RevokedAt { get; set; }
}

public class AppDb(DbContextOptions<AppDb> options) : DbContext(options)
{
    public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();

    protected override void OnModelCreating(ModelBuilder b)
    {
        b.Entity<RefreshToken>().HasIndex(t => t.TokenHash).IsUnique(); // guards against collisions and speeds up lookups
        b.Entity<RefreshToken>().HasIndex(t => t.FamilyId);             // revoking a whole family filters by it
    }
}
using System.Security.Cryptography;
using System.Text;
using Microsoft.EntityFrameworkCore;

public enum RotateStatus { Ok, Invalid, ReuseDetected }

// Database-backed refresh token store. It works with several app instances because the database,
// not an in-process lock, decides which request "wins" (a conditional UPDATE is atomic).
public class DbRefreshTokenStore(AppDb db)
{
    private static readonly TimeSpan Lifetime = TimeSpan.FromDays(7);

    // Creates and stores a new token. No "does it exist already?" check: the token has 512 bits of entropy,
    // and the unique index would reject a (practically impossible) duplicate, so we just retry.
    public async Task<string> CreateAsync(string userId, Guid familyId, CancellationToken ct = default)
    {
        for (var attempt = 0; attempt < 3; attempt++)
        {
            var raw = GenerateRaw();
            db.RefreshTokens.Add(new RefreshToken
            {
                Id = Guid.NewGuid(),
                TokenHash = Hash(raw),
                UserId = userId,
                FamilyId = familyId,
                ExpiresAt = DateTime.UtcNow.Add(Lifetime)
            });
            try
            {
                await db.SaveChangesAsync(ct);
                return raw;
            }
            catch (DbUpdateException) when (attempt < 2)
            {
                db.ChangeTracker.Clear(); // unique index violation: forget the entity and draw a new token
            }
        }
        throw new InvalidOperationException("Could not generate a unique refresh token.");
    }

    public async Task<(RotateStatus Status, string? UserId, string? NewToken)> RotateAsync(string raw, CancellationToken ct = default)
    {
        var hash = Hash(raw);
        var now = DateTime.UtcNow;
        await using var tx = await db.Database.BeginTransactionAsync(ct);

        // Atomic "claim": the condition and the change are ONE statement, so when two requests bring
        // the same token, exactly one gets 1 affected row and the other gets 0.
        var claimed = await db.RefreshTokens
            .Where(t => t.TokenHash == hash && t.UsedAt == null && t.RevokedAt == null && t.ExpiresAt > now)
            .ExecuteUpdateAsync(s => s.SetProperty(t => t.UsedAt, now), ct);

        if (claimed == 0)
        {
            var existing = await db.RefreshTokens.AsNoTracking().FirstOrDefaultAsync(t => t.TokenHash == hash, ct);
            if (existing is { UsedAt: not null, RevokedAt: null })
            {
                // An already used token came back: possible theft, so kill the whole family.
                await RevokeFamilyAsync(existing.FamilyId, ct);
                await tx.CommitAsync(ct);
                return (RotateStatus.ReuseDetected, null, null);
            }
            return (RotateStatus.Invalid, null, null); // unknown, expired or already revoked
        }

        var current = await db.RefreshTokens.AsNoTracking().FirstAsync(t => t.TokenHash == hash, ct);
        var next = await CreateAsync(current.UserId, current.FamilyId, ct); // same family, new token
        await tx.CommitAsync(ct);
        return (RotateStatus.Ok, current.UserId, next);
    }

    // Logout: revoke the whole chain.
    public async Task RevokeAsync(string raw, CancellationToken ct = default)
    {
        var hash = Hash(raw);
        var familyId = await db.RefreshTokens.Where(t => t.TokenHash == hash)
            .Select(t => (Guid?)t.FamilyId).FirstOrDefaultAsync(ct);
        if (familyId is not null) await RevokeFamilyAsync(familyId.Value, ct);
    }

    private Task<int> RevokeFamilyAsync(Guid familyId, CancellationToken ct)
    {
        var now = DateTime.UtcNow;
        return db.RefreshTokens
            .Where(t => t.FamilyId == familyId && t.RevokedAt == null)
            .ExecuteUpdateAsync(s => s.SetProperty(t => t.RevokedAt, now), ct);
    }

    private static string GenerateRaw() =>
        Convert.ToBase64String(RandomNumberGenerator.GetBytes(64)).Replace('+', '-').Replace('/', '_').TrimEnd('=');

    // SHA-256 is enough: the token is random and long (unlike a password, it cannot be brute-forced).
    private static string Hash(string raw) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(raw)));
}

What else you need in production

  • A cleanup task deleting expired tokens (keep the used ones until they expire, because they let you detect reuse).
  • Migrations instead of EnsureCreated() and a real database (PostgreSQL, SQL Server). SQLite was chosen for the example because the InMemory provider doesn't support ExecuteUpdate.
  • An index on FamilyId (it is in the example), because revoking a family filters on it.

Ready-made solutions in ASP.NET Core 8

Writing your own token server (as in the examples above) is for learning. In a real project you usually reach for a ready-made tool:

  • Identity API endpoints (.NET 8) - AddIdentityApiEndpoints<TUser>() and MapIdentityApi<TUser>() add ready-made /register, /login, /refresh, /manage/info endpoints and others, and underneath works AddBearerToken. You get an access token and a refresh token without writing code. Limitations: the tokens are not JWTs, but tickets secured by Data Protection (opaque to the client); the refresh token is stateless (there is no table, so there is no rotation, no reuse detection and no revoking of a single session, and revoking all of a user's sessions is a change of their SecurityStamp); it is a solution for your own (first-party) applications, without OpenID Connect.
  • OpenIddict (see API for companies: Client Credentials and OpenIddict) - a free, open framework for building your own OAuth 2.0 / OpenID Connect server in ASP.NET Core (not a ready-made product). It stores tokens in a database (EF Core), supports refresh token rotation and the full flows (Authorization Code + PKCE, Client Credentials).
  • Duende IdentityServer - a mature, commercial (licensed for larger companies) OIDC server.
  • An external provider (Microsoft Entra ID, Auth0, Keycloak) - the least of your own code, the token server and the storage of refresh tokens are on their side, and your API only validates the JWT.

The rule: don't write a token server yourself in production. A custom implementation makes sense when you understand the mechanism (an interview) or have very simple, closed requirements.

On the client side: one refresh at a time

A common mistake in a SPA or mobile app: several parallel requests get a 401 and each tries to refresh the token. With rotation the second refresh uses an already used token, so the server treats it as theft and invalidates the session. The solution: only one refresh at a given moment, while the other requests wait for its result:

private static readonly SemaphoreSlim Gate = new(1, 1); // only ONE refresh at a time

private async Task<string> GetFreshAccessTokenAsync(string staleToken, CancellationToken ct)
{
    await Gate.WaitAsync(ct);
    try
    {
        // another request may have already refreshed while we were waiting
        if (_tokens.AccessToken != staleToken) return _tokens.AccessToken;

        var pair = await _auth.RefreshAsync(_tokens.RefreshToken, ct); // POST /refresh
        _tokens.Save(pair);                                            // the old refresh token is now useless
        return pair.AccessToken;
    }
    finally { Gate.Release(); }
}

A good practice is also refreshing ahead of time (e.g. a minute before expiry, according to expires_in) and a short tolerance on the server side for a response that got lost on the network (the client didn't receive the new token and retries the request).

The most common pitfalls

  • A refresh token in localStorage - theft through XSS. Use an HttpOnly cookie (BFF).
  • A refresh token as a JWT with no way to revoke it - you lose the main advantage, which is control on the server side.
  • No rotation - a stolen token works until its expiry date.
  • Storing the token in the database in plain form - a database leak is a leak of all sessions.
  • Sending the refresh token to the API with resources - it should go only to the token server.
  • A race of parallel refreshes - described above.
  • No session limit and no "log out of all devices".

Interview questions

  • Why a refresh token, if there is an access token? It lets you keep the access token short (little damage after theft), while leaving the user logged in for a long time.
  • How does it differ from an access token? It is long-lived, usually opaque, goes only to the token server, and the server can easily revoke it.
  • What are refresh token rotation and reuse detection? Every token is single-use. Reusing a spent token means theft and invalidates the whole token family.
  • Where to store a refresh token in a SPA? In an HttpOnly cookie set by the backend (BFF), not in localStorage.
  • Do you need it in Client Credentials? No, the client simply fetches a new access token with its secret or certificate.
  • How do you revoke a user's access? Revoke their refresh token families. The access token will expire by itself, which is why it should live briefly.
  • Do you check in the database whether a refresh token already exists before generating it? No, the token has 512 bits of entropy, and a collision will be caught by the unique index. The check is needed when receiving a token from the client, and marking it as used has to be an atomic UPDATE.
  • Does ASP.NET Core 8 have ready-made endpoints with a refresh token? Yes, MapIdentityApi with AddBearerToken, but the tokens are stateless (no rotation or reuse detection) and there is no OIDC. For full scenarios use OpenIddict, Duende or an external provider.
  • Why do we store the hash in the database, not the token? So that a database leak doesn't reveal working tokens. SHA-256 is enough, because the token is random and long.
Buy me a coffee