3.1 KiB
3.1 KiB
Fix Login Issue - Expired JWT Tokens
Problem
You're seeing this error when trying to log in:
INFO: 127.0.0.1:58687 - "POST /auth/refresh HTTP/1.1" 401 Unauthorized
🔐 JWT decode error: Signature has expired.
This happens because the JWT refresh token stored in your browser's localStorage has expired.
Quick Fix - Option 1: Use the Clear Tokens Page
- Open your browser and navigate to:
frontend/clear-tokens.html - Click the "Clear Expired Tokens" button
- Navigate to http://localhost:5173/login
- Log in with your credentials
Quick Fix - Option 2: Clear Tokens Manually
Open your browser's Developer Console (F12) and run:
localStorage.removeItem('access_token')
localStorage.removeItem('refresh_token')
location.reload()
Quick Fix - Option 3: Clear Browser Data
- Open Developer Tools (F12)
- Go to Application tab (Chrome) or Storage tab (Firefox)
- Find Local Storage → http://localhost:5173
- Delete
access_tokenandrefresh_token - Refresh the page
What Was Fixed
1. Enhanced Token Validation
Added validateTokens() method to the auth store that:
- Decodes JWT tokens to check expiration
- Automatically clears tokens that are more than 7 days expired
- Prevents the app from trying to use invalid tokens
2. Improved Error Handling
Updated the API interceptor to:
- Better handle expired refresh tokens
- Prevent infinite retry loops
- Only redirect to login when appropriate
- Add logging for debugging
3. Startup Token Validation
Modified main.ts to:
- Validate tokens before initializing auth
- Clear expired tokens automatically on app startup
- Prevent 401 errors during initialization
Code Changes
frontend/src/stores/auth.ts
- Added
validateTokens()method - Improved error logging in
refreshAccessToken() - Better error handling in
initializeAuth()
frontend/src/services/api.ts
- Enhanced response interceptor
- Added check to prevent retrying refresh endpoint
- Better error logging
- Improved redirect logic
frontend/src/main.ts
- Added token validation on app startup
- Calls
validateTokens()beforeinitializeAuth()
Prevention
The updated code now:
- Validates tokens on startup - Clears expired tokens automatically
- Better error handling - Logs errors instead of silently failing
- Prevents retry loops - Won't retry the refresh endpoint itself
- Graceful degradation - Clears tokens and redirects to login on failure
Testing
After clearing tokens, test the following:
- ✅ Can log in with valid credentials
- ✅ Access token is stored in localStorage
- ✅ Refresh token is stored in localStorage
- ✅ Can navigate to protected routes
- ✅ Token refresh works when access token expires
- ✅ Logout clears tokens properly
Future Improvements
Consider implementing:
- Token expiration warnings - Notify users before tokens expire
- Automatic token refresh - Refresh tokens proactively before expiration
- Remember me - Longer-lived refresh tokens for persistent sessions
- Session management - Server-side session tracking