Skip to main content

Bearer Token Management

Token Management Best Practices

1. Implement Automatic Token Refresh

Access tokens are valid for 30 minutes. Refresh tokens are valid for 7 days. Implement automatic refresh logic:

// Example: Token refresh middleware
class TokenManager {
constructor(username, password, baseUrl) {
this.username = username;
this.password = password;
this.baseUrl = baseUrl;
this.token = null;
this.refreshToken = null;
this.tokenExpiry = null;
}

async getToken() {
// Refresh if token expired or will expire in the next 5 minutes
if (!this.token || Date.now() > this.tokenExpiry - 300000) {
await this.refresh();
}
return this.token;
}

async refresh() {
// Try refresh token first
if (this.refreshToken) {
try {
const r = await axios.post(`${this.baseUrl}/auth/token/refresh`, {
refreshToken: this.refreshToken,
});
this._store(r.data.data);
return;
} catch (_) { /* fall through to full login */ }
}
// Full login
const r = await axios.post(`${this.baseUrl}/auth/token`, {
username: this.username,
password: this.password,
});
this._store(r.data.data);
}

_store(data) {
this.token = data.token;
this.refreshToken = data.refreshToken;
// Access token TTL: 30 minutes
this.tokenExpiry = Date.now() + 30 * 60 * 1000;
}
}

2. Secure Credential Storage

  • ❌ Don't hardcode credentials in source code
  • ❌ Don't commit credentials to version control
  • ❌ Don't expose credentials in client-side code
  • ✅ Use environment variables
  • ✅ Use secrets management services (AWS Secrets Manager, Azure Key Vault, etc.)
  • ✅ Rotate passwords periodically

3. Handle Token Expiration Gracefully

def make_api_request(url, auth):
try:
headers = auth.get_headers()
response = requests.get(url, headers=headers)

# If token expired, refresh and retry
if response.status_code == 401:
auth.token = None # Force token refresh
headers = auth.get_headers()
response = requests.get(url, headers=headers)

return response
except Exception as e:
# Handle errors appropriately
raise

4. Use Different Credentials Per Environment

  • Separate credentials for sandbox and production
  • Different credentials for different applications
  • Makes it easier to revoke access if compromised

5. Monitor API Usage

  • Regularly review API usage logs
  • Set up alerts for failed authentication attempts
  • Monitor for unusual activity patterns

Last updated: October 2025