Skip to main content

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.
Not for API Calls: This token is NOT used for authenticating API requests. It’s exclusively for OAuth flow coordination.

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 the Authorization: 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

Recommended: HTTP-only Cookies
Alternative: Memory Storage (for SPAs)
Avoid localStorage for sensitive applications: XSS attacks can steal tokens from localStorage. Use HTTP-only cookies or memory storage instead.

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.
Security for Financial Operations: Given that this API handles sensitive financial operations (setting PINs, adding funds, connecting wallets, card management), the refresh token lifetime is intentionally short at 7 days. This aligns with modern banking security standards where US financial institutions now require re-authentication after 15 minutes of inactivity.
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

Critical Security Requirement: Certain privileged operations require step-up authentication regardless of token validity. Users must re-authenticate immediately before performing these actions.
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
Implementation:

Refresh Flow

Response:
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

Standard Login Access TokensLogin access tokens from 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
When OTP Fails:
Best Practice:
  • 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:
Failure Scenarios:
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)
Always use:
  • HTTP-only cookies (web)
  • SecureStore (React Native)
  • Keychain (iOS)
  • EncryptedSharedPreferences (Android)
OWASP Guidance: Review OWASP Session Management Cheat Sheet and OWASP HTML5 Security Cheat Sheet for comprehensive security guidance.

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

XSS Vulnerability Risk: A single Cross-Site Scripting (XSS) attack can steal ALL tokens stored in localStorage or sessionStorage. These storage mechanisms are always accessible to JavaScript running on your page.
HTTP-only cookies provide the strongest protection against XSS attacks:
OWASP Cookie Security Attributes:
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 (requires Secure flag)

Memory Storage (Alternative for SPAs)

For Single-Page Applications where cookies aren’t feasible, use in-memory storage:
Memory Storage Limitation: Tokens are lost on page refresh. You’ll need to implement a refresh mechanism or use short-lived sessions. This trade-off prioritizes security over convenience.

localStorage: Last Resort Only

⚠️ Use Only If Absolutely Necessary: localStorage should be avoided for token storage. If you must use it, implement these additional protections:
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.
OWASP Mobile Top 10 - M9: Insecure data storage is one of the top mobile security risks. Never store tokens in:
  • AsyncStorage (React Native)
  • Plain SharedPreferences (Android)
  • UserDefaults (iOS)
  • Application sandboxed directories without encryption

iOS: Keychain Services

iOS Keychain Accessibility Options:

Android: Keystore & EncryptedSharedPreferences

Android Security Features:
  • 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)
  • Secure flag set on all cookies (HTTPS only)
  • SameSite=Strict or Lax set on cookies
  • Narrow Domain and Path cookie 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
Mobile Applications:
  • 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
General:
  • 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

Cause: Refresh token expired (7 days) or was revoked.Solution:
  • Clear all tokens from storage
  • Redirect user to login
  • Restart OAuth flow from Step 1
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
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
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
Security Testing: See the comprehensive OWASP Security Checklist above for platform-specific security requirements including:
  • 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