# 22. Token Refresh & Session Management meta: id: ios-production-22 feature: ios-production priority: P1 depends_on: [ios-production-21] tags: [backend, auth, production] objective: - Implement automatic token refresh and robust session management to prevent unexpected logouts deliverables: - Token refresh interceptor in APIClient - Silent re-authentication flow - Session expiry handling - Concurrent request queue during refresh steps: 1. Implement token refresh: - Add refresh token endpoint to backend if not exists - Modify APIClient to detect 401 responses - On 401, attempt token refresh with refresh token - Retry original request with new token 2. Handle concurrent requests: - Queue requests while refresh in progress - Don't duplicate refresh requests - Use Combine or async/await for coordination 3. Add silent re-authentication: - If refresh fails, try biometric re-auth - If biometric fails, prompt for password - If all fail, logout user 4. Implement session expiry: - Parse JWT expiry claim - Proactively refresh before expiry (5 min buffer) - Schedule background refresh 5. Add session monitoring: - Track session age - Alert user when session nearing expiry - Auto-refresh on app foreground 6. Handle edge cases: - Refresh token also expired → full re-auth - Network unavailable during refresh → queue and retry - Multiple tabs/apps refreshing simultaneously 7. Update AuthService: - Expose session state - Handle refresh failures gracefully - Notify UI of re-authentication needs tests: - Unit: Test token refresh logic - Integration: Test concurrent request handling - E2E: Test session expiry and refresh acceptance_criteria: - Token refresh automatic and transparent to user - Concurrent requests queued during refresh, not failed - Proactive refresh 5 minutes before expiry - Biometric re-auth offered if refresh fails - Session restored on app relaunch (if tokens valid) - Graceful logout if all auth methods fail - No duplicate refresh requests - Background refresh on app foreground - Unit tests covering all refresh scenarios validation: - Wait for token expiry → app refreshes automatically - Trigger 401 → refresh attempted, request retried - Revoke refresh token → app prompts re-auth - Background app → foreground → token refreshed if needed - Check logs → no duplicate refresh requests notes: - Current APIClient has retry logic but no token refresh - Backend must support refresh token endpoint - Consider using OAuth 2.0 refresh token flow - Store refresh token with higher security than access token