CodexBloom - Programming Q&A Platform

ASP.NET Core 6: How to properly invalidate JWT tokens in a distributed environment?

πŸ‘€ Views: 37 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
ASP.NET Core JWT Authentication Distributed Systems C#

Quick question that's been bugging me - I'm having a hard time understanding I've been researching this but I am currently developing an ASP.NET Core 6 application that uses JWT tokens for authentication. The application is deployed in a distributed environment with multiple instances behind a load balancer. I need to implement a way to invalidate tokens when a user logs out or when their privileges change, but I'm struggling with how to manage this effectively across all instances. Currently, I am storing the JWT in-memory on the server side for verification. However, this approach seems to break when I scale up my application, as each server instance has its own memory space. When a user logs out, I remove the token from the in-memory store, but the other instances still consider it valid. I have explored using a distributed cache like Redis to store invalidated tokens, but I'm concerned about performance and the potential for it to become a bottleneck if there are many invalidation requests. Here’s a simplified version of my current logout endpoint: ```csharp [HttpPost("/logout")] public async Task<IActionResult> Logout() { var token = Request.Headers["Authorization"].ToString().Replace("Bearer ", ""); await _tokenService.InvalidateTokenAsync(token); return Ok(); } ``` I’m unsure about the best practices for implementing token invalidation in a distributed setup. Any suggestions on how to efficiently manage JWT token invalidation or how to architect this feature would be greatly appreciated! I'm also open to any other approaches that could work better in a distributed scenario. Additionally, I received an behavior `"Token not found in cache"` when trying to invalidate a token that was removed from one instance. How can I ensure that all instances are in sync regarding token validity status? I'm working on a REST API that needs to handle this. Any ideas what could be causing this? Cheers for any assistance! I'm working with C# in a Docker container on Windows 11. Any suggestions would be helpful.