79 lines
2.6 KiB
Markdown
79 lines
2.6 KiB
Markdown
# 22. Token Refresh & Session Management
|
|
|
|
meta:
|
|
id: android-production-22
|
|
feature: android-production
|
|
priority: P1
|
|
depends_on: [android-production-21]
|
|
tags: [backend, auth, production]
|
|
|
|
objective:
|
|
- Implement automatic token refresh and robust session management to prevent unexpected logouts
|
|
|
|
deliverables:
|
|
- OkHttp authenticator for token refresh
|
|
- Token refresh interceptor
|
|
- Silent re-authentication flow
|
|
- Session expiry handling
|
|
|
|
steps:
|
|
1. Implement OkHttp authenticator:
|
|
- Add Authenticator to OkHttp client in NetworkModule.kt
|
|
- Detect 401 responses
|
|
- Attempt refresh with refresh token
|
|
- Retry original request with new token
|
|
2. Handle concurrent requests:
|
|
- Use Mutex or synchronized block to prevent duplicate refresh
|
|
- Queue requests while refresh in progress
|
|
- Use Kotlin coroutines for async coordination
|
|
3. Add token refresh endpoint:
|
|
- Ensure backend supports refresh token endpoint
|
|
- Implement refresh in AuthRepository
|
|
- Store new access and refresh tokens
|
|
4. Implement proactive refresh:
|
|
- Parse JWT expiry claim
|
|
- Refresh 5 minutes before expiry
|
|
- Schedule refresh on app foreground
|
|
5. Handle edge cases:
|
|
- Refresh token expired → logout user
|
|
- Network unavailable → queue and retry
|
|
- Refresh fails → prompt re-authentication
|
|
6. Update AuthViewModel:
|
|
- Expose session state
|
|
- Handle refresh failures gracefully
|
|
- Auto-logout on persistent auth failures
|
|
7. Add tests:
|
|
- Test token refresh logic
|
|
- Test concurrent request handling
|
|
- Test session expiry scenarios
|
|
|
|
tests:
|
|
- Unit: Test authenticator with MockWebServer
|
|
- Integration: Test refresh flow end-to-end
|
|
- E2E: Test session expiry behavior
|
|
|
|
acceptance_criteria:
|
|
- Token refresh automatic and transparent to user
|
|
- Concurrent requests queued during refresh
|
|
- 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
|
|
- MockWebServer tests for authenticator
|
|
|
|
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:
|
|
- OkHttp Authenticator is the standard way to handle 401s
|
|
- Use EncryptedSharedPreferences for token storage
|
|
- Consider using Credential Manager for modern auth (API 34+)
|
|
- Backend must support refresh token endpoint
|