Introduction
In a JWT-based API, access tokens are usually kept short-lived. This limits the period during which a stolen token can be used. However, forcing a user to enter a username and password every time an access token expires creates a poor user experience. A refresh token mechanism allows the server to renew a valid session without repeating the full sign-in process.
In this lesson, we will build a practical flow that uses ASP.NET Core Identity for user validation and MSSQL for secure refresh-token persistence. The sample uses a 15-minute access token and a 30-day refresh token. Every successful refresh rotates the token, revokes the previous value, and creates a replacement. If a revoked token is presented again, the entire token family is terminated as a possible replay or theft response.
The refresh-token model
After a successful login, the client receives two values:
- Access token: Sent to protected API endpoints in an
Authorization: Bearer ...header. It is short-lived and validated by the API. - Refresh token: Sent only to the refresh endpoint to obtain a new access token. It is long-lived, randomly generated and should not contain API permissions.
A refresh token does not need to be a JWT. A practical design generates a cryptographically secure random value, returns the raw value to the client, and stores only a hash in the database. If the database is exposed, an attacker cannot directly use the stored hash as a refresh credential.
| Stage | Server action | Client action |
|---|---|---|
| Login | Validate the user and issue an access-token and refresh-token pair. | Store the pair using a secure client strategy. |
| API request | Validate the access token. | Send the access token in the Authorization header. |
| Refresh | Hash and locate the refresh token, validate it and rotate it. | Send the old token once. |
| Logout or revocation | Mark the token as revoked. | Remove local token data. |
Database model
Using a dedicated table makes expiration, device information, revocation reason and token-family tracking explicit. The following entity is compatible with the ApplicationUser and ApplicationDbContext introduced earlier.
public sealed class RefreshToken
{
public long Id { get; set; }
public string UserId { get; set; } = null!;
public ApplicationUser User { get; set; } = null!;
public string TokenHash { get; set; } = null!;
public string FamilyId { get; set; } = null!;
public DateTime ExpiresAtUtc { get; set; }
public DateTime CreatedAtUtc { get; set; }
public DateTime? RevokedAtUtc { get; set; }
public string? ReplacedByTokenHash { get; set; }
public string? RevocationReason { get; set; }
public bool IsActive(DateTime nowUtc) =>
RevokedAtUtc is null && ExpiresAtUtc > nowUtc;
}FamilyId groups tokens derived from the same initial session. During rotation, the new token replaces the old one. If the old token is presented again, that is not merely an expiration event; it can indicate replay or token theft.
Add indexes for hash lookups and family queries:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<RefreshToken>()
.HasIndex(x => x.TokenHash)
.IsUnique();
builder.Entity<RefreshToken>()
.HasIndex(x => new { x.UserId, x.FamilyId });
builder.Entity<RefreshToken>()
.Property(x => x.TokenHash)
.HasMaxLength(64)
.IsRequired();
}Create and apply an Entity Framework Core migration. In production, migrations should be part of a controlled deployment process rather than being automatically applied every time the application starts.
Generating and hashing the token
Use RandomNumberGenerator to create refresh tokens. User email addresses, timestamps and predictable combinations of GUIDs are not suitable token generators.
using System.Security.Cryptography;
using System.Text;
public interface IRefreshTokenService
{
string CreateRawToken();
string Hash(string rawToken);
}
public sealed class RefreshTokenService : IRefreshTokenService
{
public string CreateRawToken()
{
var bytes = RandomNumberGenerator.GetBytes(64);
return Convert.ToBase64UrlString(bytes);
}
public string Hash(string rawToken)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(rawToken));
return Convert.ToHexString(bytes).ToLowerInvariant();
}
}The raw value is used only in the login or refresh response. The database receives Hash(rawToken). Because the hash is one-way, the original refresh token cannot be reconstructed later; rotation generates a new raw value.
Issuing the token pair during login
The login endpoint should first validate the user with UserManager or SignInManager. Tokens must not be issued before this validation succeeds. The JWT service from the previous lesson can create the access token.
public sealed record TokenResponse(
string AccessToken,
DateTime AccessTokenExpiresAtUtc,
string RefreshToken,
DateTime RefreshTokenExpiresAtUtc);
private async Task<TokenResponse> IssueTokenPairAsync(
ApplicationUser user, CancellationToken cancellationToken)
{
var now = DateTime.UtcNow;
var rawRefreshToken = _refreshTokenService.CreateRawToken();
var refreshToken = new RefreshToken
{
UserId = user.Id,
TokenHash = _refreshTokenService.Hash(rawRefreshToken),
FamilyId = Guid.NewGuid().ToString("N"),
CreatedAtUtc = now,
ExpiresAtUtc = now.AddDays(30)
};
_db.RefreshTokens.Add(refreshToken);
await _db.SaveChangesAsync(cancellationToken);
var accessExpires = now.AddMinutes(15);
var accessToken = _jwtTokenService.CreateAccessToken(user, accessExpires);
return new TokenResponse(
accessToken,
accessExpires,
rawRefreshToken,
refreshToken.ExpiresAtUtc);
}The refresh token must be sent over HTTPS. For browser applications, storage must be selected according to the threat model. A token readable by JavaScript in localStorage can be stolen if an XSS vulnerability exists. In some architectures, an HttpOnly, Secure cookie with suitable SameSite settings is preferable; cookie-based flows must also include CSRF protection.
Refresh endpoint and rotation
The refresh endpoint receives the raw value, hashes it and looks up the record. If the record does not exist or has expired, return 401 Unauthorized. A previously revoked token should be treated as a reuse-detection event.
public sealed record RefreshRequest(string RefreshToken);
[HttpPost("refresh")]
[AllowAnonymous]
public async Task<ActionResult<TokenResponse>> Refresh(
RefreshRequest request, CancellationToken cancellationToken)
{
var now = DateTime.UtcNow;
var hash = _refreshTokenService.Hash(request.RefreshToken);
var current = await _db.RefreshTokens
.Include(x => x.User)
.SingleOrDefaultAsync(x => x.TokenHash == hash, cancellationToken);
if (current is null)
return Unauthorized();
if (current.RevokedAtUtc is not null)
{
await RevokeFamilyAsync(current.FamilyId, now,
"Refresh token reuse detected", cancellationToken);
return Unauthorized();
}
if (current.ExpiresAtUtc <= now)
return Unauthorized();
var replacementRaw = _refreshTokenService.CreateRawToken();
var replacementHash = _refreshTokenService.Hash(replacementRaw);
current.RevokedAtUtc = now;
current.RevocationReason = "Rotated";
current.ReplacedByTokenHash = replacementHash;
var replacement = new RefreshToken
{
UserId = current.UserId,
TokenHash = replacementHash,
FamilyId = current.FamilyId,
CreatedAtUtc = now,
ExpiresAtUtc = now.AddDays(30)
};
_db.RefreshTokens.Add(replacement);
await _db.SaveChangesAsync(cancellationToken);
var accessExpires = now.AddMinutes(15);
var accessToken = _jwtTokenService
.CreateAccessToken(current.User, accessExpires);
return Ok(new TokenResponse(
accessToken, accessExpires,
replacementRaw, replacement.ExpiresAtUtc));
}In a production system, two simultaneous refresh requests require additional concurrency handling. A database transaction, optimistic concurrency field or atomic update can prevent the same token from being accepted twice. Without such protection, a seemingly correct rotation algorithm may issue two replacement tokens.
Revocation and reuse detection
During logout, revoke the submitted refresh token. For a “sign out everywhere” operation, revoke all active tokens for the user. If the password changes or account compromise is suspected, terminating token families provides an effective emergency control.
private async Task RevokeFamilyAsync(
string familyId,
DateTime nowUtc,
string reason,
CancellationToken cancellationToken)
{
await _db.RefreshTokens
.Where(x => x.FamilyId == familyId && x.RevokedAtUtc == null)
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.RevokedAtUtc, nowUtc)
.SetProperty(x => x.RevocationReason, reason),
cancellationToken);
}After reuse detection, revoke all active records in the family, not only the record that was reused. If an attacker can present an old token, the replacement held by the legitimate client may also be at risk.
Expiration, cleanup and security controls
- Keep access tokens short-lived and set refresh-token lifetime according to the business and security requirements.
- Never store raw refresh tokens, passwords or JWT signing secrets in the refresh-token table.
- Do not put sensitive personal data or unnecessary permissions into JWT payloads.
- Run the refresh endpoint over HTTPS and avoid verbose errors that reveal whether a token exists.
- Remove or archive expired token records with a scheduled cleanup process. Follow organizational audit and retention policies.
- IP addresses and User-Agent values may support monitoring, but they should not be the sole authentication factor.
- When a password changes, consider calling
UpdateSecurityStampAsyncand revoking refresh-token families together.
When multiple application instances are deployed, all instances must access the same token store and JWT signing keys must be managed through a secure shared key-management strategy. ASP.NET Core Data Protection keys also need durable and protected storage in distributed environments; temporary local keys can cause unexpected validation failures after restarts.
Common mistakes
- Designing the refresh token as a JWT: This adds payload and signing complexity without a clear benefit. An opaque, random and server-tracked value is usually simpler.
- Storing plaintext: A database breach immediately exposes every active session.
- Skipping rotation: A stolen long-lived token can be reused until it expires.
- Only rejecting a revoked token: Failing to revoke the family after reuse detection may allow an attack to continue.
- Ignoring password changes: Existing sessions may remain active longer than intended.
- Ignoring race conditions: Concurrent acceptance of one refresh token weakens the single-use guarantee.
Practice exercise
Extend the JWT API from the previous lessons with the RefreshToken entity and an EF Core migration. Then complete these tasks:
- Return a 15-minute access token and a 30-day refresh token from the login endpoint.
- Implement hash lookup and rotation in the refresh endpoint.
- When an old refresh token is submitted a second time, revoke every active token in its family.
- Add a logout endpoint that revokes only the submitted refresh token.
- Write a cleanup query for expired records and test concurrent refresh requests with a transaction or concurrency check.
Test successful renewal, an invalid token, an expired token, a revoked token, token reuse and two parallel requests as separate cases.
Conclusion
A refresh-token mechanism combines the security benefits of short-lived access tokens with a smoother user experience. A reliable implementation is more than generating a new token: hashing, expiration, rotation, revocation, family tracking, reuse detection and concurrency control must work together. ASP.NET Core Identity manages the user lifecycle, while a dedicated refresh-token store makes API sessions observable and revocable when necessary.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/security/authentication/configure-jwt-bearer-authentication
- https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration
- https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/introduction
- https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator