CodexBloom - Programming Q&A Platform

Issues with OAuth2 Implicit Flow Token Expiration in a React App using ASP.NET Core 6

👀 Views: 40 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
aspnet-core oauth2 react jwt JavaScript

I keep running into I'm attempting to set up I'm relatively new to this, so bear with me... I'm working on a React application that uses OAuth2 implicit flow for authentication against an ASP.NET Core 6 backend. I have set up the authentication flow, but I'm having issues with token expiration. The access token is supposed to expire after 1 hour, but I notice that users are still able to make API calls even after the token is expired for a few minutes, which shouldn't be the case. I've implemented the following configuration in my `Startup.cs`: ```csharp services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "https://yourissuer.com", ValidAudience = "https://youraudience.com", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")) }; }); ``` In my React app, I am storing the access token in local storage and making API calls using Axios with an interceptor to add the token to the `Authorization` header: ```javascript axios.interceptors.request.use(config => { const token = localStorage.getItem('access_token'); if (token) { config.headers['Authorization'] = `Bearer ${token}`; } return config; }); ``` I also handle the token expiration by checking the expiration time when making requests: ```javascript const isTokenExpired = (token) => { const payload = JSON.parse(atob(token.split('.')[1])); return payload.exp * 1000 < Date.now(); }; ``` When the token is expired, I try to redirect the user to the login page. However, the API still responds with valid data for a short period after the expiration. I suspect there might be some caching issue or a mismatch in the clock between my app and the server. I've tried clearing the cache and ensuring that the server's clock is synchronized, but the issue persists. What could be causing this delay in recognizing token expiration, and how can I ensure that expired tokens are properly rejected? I'm coming from a different tech stack and learning Javascript. This issue appeared after updating to Javascript 3.9. Has anyone else encountered this? I'm developing on Ubuntu 22.04 with Javascript. I'd really appreciate any guidance on this.