Overview
Understanding token lifecycle management is critical for building reliable applications. This guide covers everything you need to know about handling JWT tokens, access tokens, and refresh tokens throughout your application’s lifecycle.Token Types
The API uses three distinct token types, each serving a specific purpose:JWT Token
OAuth Flow Session
- Lifetime: 10 minutes
- Purpose: OAuth flow coordination
- Usage: Only during OAuth authorization
- Not for API calls
Access Token
API Authentication
- Lifetime: 6 hours
- Purpose: Authenticate API requests
- Usage: All authenticated endpoints
- Include in Authorization header
Refresh Token
Token Renewal
- Lifetime: 7 days
- Purpose: Obtain new access tokens
- Usage: Token refresh endpoint
- Store securely, never expose
Token Lifecycle
JWT Token (OAuth Session)
Purpose
The JWT token is used only during the OAuth authorization flow to maintain session state between OAuth steps.Characteristics
Usage Example
Expiration Handling
Access Token (API Authentication)
Purpose
Access tokens authorize your application to make API requests on behalf of the user. Include them in theAuthorization: Bearer header to perform user-authorized operations.
Acting on Behalf of Users: Access tokens represent the user’s grant of permission for your application to interact with their account. Use them only for actions the user has authorized.
Characteristics
Usage
Storage
- Web Applications
- Mobile Applications
- Server-Side
Recommended: HTTP-only CookiesAlternative: Memory Storage (for SPAs)
Expiration Detection
Best Practice: Refresh tokens 60 seconds before expiry to account for network latency and clock differences.
Refresh Token (Token Renewal)
Purpose
Refresh tokens allow you to obtain new access tokens without requiring the user to re-authenticate, providing a balance between security and user convenience.With Biometric Authentication: If your application implements FaceID, TouchID, or credential saving, the 7-day refresh token lifetime provides a good balance between security and user experience. Users authenticate frequently with biometrics while maintaining secure access.
Characteristics
Step-Up Authentication for Privileged Operations
Privileged operations requiring step-up authentication:- Setting or changing PIN codes
- Adding or withdrawing funds
- Connecting new wallets (custodial or non-custodial)
- Card activation or sensitive card operations
- Updating security settings
- Large transactions above threshold
Refresh Flow
Token Rotation: The API returns a NEW refresh token with each refresh. Always update your stored refresh token.
Automatic Refresh Strategy
Implement automatic token refresh in your API client:Token Revocation
Understanding when and how to revoke tokens is crucial for security and user experience:Token Revocation Policies
- Login Flow Tokens
- OAuth Flow Tokens
- Revocation Decision Tree
Standard Login Access TokensLogin access tokens from When OTP Fails:Best Practice:
POST /v1/auth/login are short-lived and irrevocable:Key Points:
- Access tokens expire after 6 hours automatically
- No explicit revocation needed on login failure
- Tokens naturally expire if not used
- Cannot be refreshed - user must re-authenticate
- Allow multiple OTP retry attempts
- No revocation necessary - tokens expire naturally
- Clear tokens from local storage on user logout only
OAuth Token Revocation Implementation
Revoke OAuth tokens when users log out or revoke app access:Revocation Response
Success:Effect of OAuth Revocation: Both access and refresh tokens become invalid immediately. Users must complete the OAuth flow again to regain access.
Best Practices for Token Revocation
Always Clear Local Storage
Even if the API revocation call fails, always clear tokens from local storage to prevent unauthorized access.
Handle Revocation Failures Gracefully
Network issues shouldn’t block logout. Log the error and continue.
Don't Revoke on Retry Scenarios
Failed OTP or temporary errors should allow retry without revocation.
Revoke on Security Events
Immediately revoke tokens when security issues are detected.
Best Practices
1. Proactive Refresh
Refresh Before Expiry
Don’t wait for a 401 error. Refresh tokens 60 seconds before they expire to ensure uninterrupted service.
2. Race Condition Prevention
Prevent Concurrent Refreshes
Use locks or flags to prevent multiple simultaneous refresh requests.
3. Secure Storage
Use Platform Secure Storage
Never store tokens in:
- localStorage (web)
- AsyncStorage (React Native)
- Plain SharedPreferences (Android)
- UserDefaults (iOS)
- HTTP-only cookies (web)
- SecureStore (React Native)
- Keychain (iOS)
- EncryptedSharedPreferences (Android)
OWASP Security Best Practices
The following recommendations align with OWASP (Open Web Application Security Project) security standards for token storage and session management.Web Applications
Cookie-Based Storage (Recommended)
HTTP-only cookies provide the strongest protection against XSS attacks:SameSite Options:
Strict: Cookie never sent on cross-site requests (most secure)Lax: Cookie sent on top-level navigation (GET requests)None: Cookie sent on all requests (requiresSecureflag)
Memory Storage (Alternative for SPAs)
For Single-Page Applications where cookies aren’t feasible, use in-memory storage:localStorage: Last Resort Only
OWASP Encryption Standards:
- Use AES-256-GCM for symmetric encryption (minimum 128-bit, prefer 256-bit)
- Use secure key derivation (PBKDF2, scrypt, or Argon2)
- Never hardcode encryption keys
- Rotate keys regularly
Mobile Applications
Mobile apps must use platform-native secure storage mechanisms to leverage hardware-backed encryption.iOS: Keychain Services
Android: Keystore & EncryptedSharedPreferences
- Hardware-Backed Keystore: Keys stored in Trusted Execution Environment (TEE) or Secure Element
- AES-256-GCM Encryption: Industry-standard authenticated encryption
- Key Derivation: EncryptedSharedPreferences handles key generation and rotation
- Biometric Binding: Optional binding to device biometrics
Additional Security Measures
Transport Security
HTTPS Everywhere
- Always use HTTPS for token transmission
- Implement certificate pinning for mobile apps
- Validate SSL/TLS certificates
- Use TLS 1.2 or higher
Token Binding
Additional Context ValidationBind tokens to additional user context:
- Device fingerprint
- IP address (with caution)
- User-Agent string
- Geolocation (for high-risk operations)
Token Rotation
Regular Token Rotation
- Refresh tokens before expiry
- Rotate refresh tokens on each use
- Implement token versioning
- Revoke old tokens immediately
Logging & Monitoring
Security Event LoggingLog security-relevant events:
- Token issuance
- Token refresh attempts
- Failed authentication
- Token revocation
- Unusual access patterns
OWASP Security Checklist
Use this checklist to ensure your token storage implementation follows OWASP best practices: Web Applications:- Tokens stored in HTTP-only cookies (not localStorage)
-
Secureflag set on all cookies (HTTPS only) -
SameSite=StrictorLaxset on cookies - Narrow
DomainandPathcookie attributes - Cookies expire with token lifetime
- HTTPS used for entire application
- XSS protection headers implemented (
X-XSS-Protection,Content-Security-Policy) - Tokens never logged or exposed in URLs
- iOS: Tokens stored in Keychain with
kSecAttrAccessibleWhenUnlockedThisDeviceOnly - Android: Tokens stored using EncryptedSharedPreferences with AES-256-GCM
- No tokens stored in AsyncStorage, SharedPreferences, or UserDefaults
- Certificate pinning implemented
- Root/jailbreak detection implemented
- No tokens in application logs or crash reports
- Tokens cleared on app uninstall or logout
- Access tokens short-lived (6 hours or less)
- Refresh tokens limited lifetime (7 days for financial apps)
- Token refresh implemented with 60-second buffer
- Automatic logout on token expiry
- Token revocation on logout
- No tokens in version control or environment files
- Encryption keys rotated regularly
- Security event logging implemented
Compliance Note: For applications handling financial data or PHI (Protected Health Information), additional requirements may apply under PCI DSS, HIPAA, or regional regulations (GDPR, CCPA).
4. Error Handling
Handle Refresh Failures Gracefully
When refresh fails, clear tokens and redirect to login:
5. Token Cleanup
Clear Tokens on Logout
Always clear tokens from storage when users log out:
Troubleshooting
Token confusion (using wrong token)
Token confusion (using wrong token)
Symptom: 401 errors despite having valid tokens.Solution:
- JWT Token: Only for OAuth flow (Step 3 body in API mode)
- Access Token (login): Only for Step 3 Authorization header (API mode)
- Access Token (final): For all subsequent API calls
- Refresh Token: Only for token refresh endpoint
Multiple refresh requests
Multiple refresh requests
Cause: Race condition when multiple API calls detect expiry simultaneously.Solution:
- Implement refresh lock/flag
- Return same promise for concurrent refresh calls
- Queue API calls during refresh
Clock skew issues
Clock skew issues
Cause: Server and client clocks are out of sync.Solution:
- Add 60-second buffer before expiry
- Use server time in responses when possible
- Handle 401s gracefully with automatic retry
Testing Checklist
Functional Testing:- Tokens stored in secure storage
- Access token automatically refreshes before expiry
- Refresh token failure triggers re-authentication
- Concurrent API calls don’t cause multiple refreshes
- 401 errors trigger token refresh and retry
- Logout clears all tokens from storage
- Token expiry has 60-second buffer
- Revocation invalidates tokens immediately
- Token confusion doesn’t occur (right token in right place)
- Clock skew doesn’t cause premature expiry
- Web application cookie security
- Mobile platform secure storage verification
- Transport security and encryption
- Compliance requirements
Next Steps
Security Best Practices
Essential security guidelines for production
Troubleshooting Guide
Common issues and solutions
Hosted UI Flow
Implement OAuth with hosted authentication
API Mode Flow
Implement OAuth with custom UI