Lesson 7 of 8
Token Revocation & Blacklisting
JWTs are stateless - once issued, they're valid until expiry even if the user changes their password or is banned. For security-critical operations (forced logout, account suspension), you need a token revocation mechanism: Redis blacklisting by JTI.
JWT Revocation via Redis JTI Blacklist
// ━━ Token revocation service ━━
public class JwtRevocationService(IConnectionMultiplexer redis)
{
private readonly IDatabase _db = redis.GetDatabase();
// Revoke a token by adding its JTI to Redis blacklist
public async Task RevokeTokenAsync(string jti, DateTime expiry)
{
var ttl = expiry - DateTime.UtcNow;
if (ttl > TimeSpan.Zero)
await _db.StringSetAsync($"revoked:jti:{jti}", "1", ttl); // auto-expires → no cleanup needed
}
// Check if a token's JTI is blacklisted
public async Task<bool> IsRevokedAsync(string jti) =>
await _db.KeyExistsAsync($"revoked:jti:{jti}");
}
// ━━ JwtBearer event to check blacklist ━━
options.Events = new JwtBearerEvents
{
OnTokenValidated = async context =>
{
var jti = context.Principal!.FindFirstValue(JwtRegisteredClaimNames.Jti);
if (jti is null)
{
context.Fail("Token missing JTI claim");
return;
}
var revocationService = context.HttpContext.RequestServices
.GetRequiredService<JwtRevocationService>();
if (await revocationService.IsRevokedAsync(jti))
{
context.Fail("Token has been revoked");
return;
}
}
};
// ━━ Revoke all tokens for user (password change / account ban) ━━
public class UserService(
UserManager<ApplicationUser> userManager,
JwtRevocationService revocation)
{
public async Task ChangePasswordAsync(string userId, string newPassword, CancellationToken ct)
{
var user = await userManager.FindByIdAsync(userId)
?? throw new NotFoundException("User", userId);
var token = await userManager.GeneratePasswordResetTokenAsync(user);
var result = await userManager.ResetPasswordAsync(user, token, newPassword);
if (!result.Succeeded)
throw new ValidationException("Password change failed");
// Update Security Stamp - invalidates ALL existing sessions
// (only works if you validate SecurityStamp in JWT validation)
await userManager.UpdateSecurityStampAsync(user);
// Note: individual JTI revocation via Redis only needed for active access tokens
// Refresh tokens are already invalidated via RefreshToken table
}
}
// ━━ Admin: ban a user ━━
[HttpPost("{userId}/ban"), Authorize(Roles = "Admin")]
public async Task<IActionResult> BanUser(string userId)
{
var user = await userManager.FindByIdAsync(userId);
if (user is null) return NotFound();
// Lock account
await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue);
user.IsActive = false;
await userManager.UpdateAsync(user);
// Force re-login by updating security stamp
await userManager.UpdateSecurityStampAsync(user);
return Ok(new { message = $"User {userId} banned" });
}
class ApplicationUser { public string Id { get; set; } = ""; public bool IsActive { get; set; } }
class NotFoundException : Exception { public NotFoundException(string r, object id) : base($"{r} {id}") { } }
class ValidationException : Exception { public ValidationException(string m) : base(m) { } }
interface IConnectionMultiplexer { IDatabase GetDatabase(); }
interface IDatabase { Task StringSetAsync(string key, string val, TimeSpan? expiry = null); Task<bool> KeyExistsAsync(string key); }Tip
Tip
Practice Token Revocation Blacklisting in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Token Revocation Blacklisting 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 Token Revocation Blacklisting is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?